猿问
Java中A类的数组如何传入B类???急
就是A类中的数组已经赋了值,如何把整个数组传入B类中而且可以使用
慕粉2023498883
浏览 1840
回答 1
1回答
frece
public class Test { public static void main(String[] args) { //方法一:引用传递 //创建A对象并给数组赋值 A a = new A(); //得到A对象的数组 int[] aArr = a.getIntArr(); System.out.println("引用传递的A数组: "); for (int i = 0; i < aArr.length; i++) { System.out.print(aArr[i] + " "); } //创建B对象并给数组赋值 B b = new B(); b.setIntArr(aArr); System.out.println("\n引用传递的B数组: "); int[] bArr = b.getIntArr(); for (int i = 0; i < bArr.length; i++) { System.out.print(bArr[i] + " "); } //改变B数组,A数组也会随之变化 bArr[2] = 666; System.out.println("\n引用传递改变值之后的A数组: "); for (int i = 0; i < aArr.length; i++) { System.out.print(aArr[i] + " "); } System.out.println("\n引用传递改变值之后的B数组: "); for (int i = 0; i < bArr.length; i++) { System.out.print(bArr[i] + " "); } //方法二:值传递 A aa = new A(); int[] aaArr = aa.getIntArr(); int[] tempArr = new int[aaArr.length]; System.out.println("\n值传递的A数组: "); for (int i = 0; i < tempArr.length; i++) { tempArr[i] = aaArr[i]; System.out.print(aaArr[i] + " "); } //创建B对象并给数组赋值 B bb = new B(); bb.setIntArr(tempArr); System.out.println("\n值传递的B数组: "); int[] bbArr = bb.getIntArr(); for (int i = 0; i < bbArr.length; i++) { System.out.print(bbArr[i] + " "); } //改变B数组,A数组不会随之变化 bbArr[2] = 666; System.out.println("\n值传递改变值之后的A数组: "); for (int i = 0; i < aaArr.length; i++) { System.out.print(aaArr[i] + " "); } System.out.println("\n值传递改变值之后的B数组: "); for (int i = 0; i < bbArr.length; i++) { System.out.print(bbArr[i] + " "); } } } class A{ private int[] intArr = {1,2,3,4,5}; //get().. set().. public int[] getIntArr() { return intArr; } public void setIntArr(int[] intArr) { this.intArr = intArr; } } class B{ private int[] intArr ; //get().. set().. public int[] getIntArr() { return intArr; } public void setIntArr(int[] intArr) { this.intArr = intArr; } }要保证B类和A类中有相同类型的数组昂
0
0
0
随时随地看视频
慕课网APP
相关分类
Java
我要回答