java 返回2个数组_java – 如何从方法返回多个数组?

假设我想从一个方法返回6个数组(在另一个类中).

这样做的最佳方式是什么?为什么?

这就是我到目前为止所拥有的.

public Object getData()throws FileNotFoundException{

counter = 0;

Scanner f = new Scanner(new File("Contacts.txt")).useDelimiter(",");

while (f.hasNext()){

firstNames[counter] = f.next();

lastNames[counter] = f.next();

emailList[counter] = f.next();

ageList[counter] = f.next();

imgLoc[counter] = f.nextLine();

counter++;

}

f.close();

firstNames = Arrays.copyOf(firstNames, counter);

lastNames = Arrays.copyOf(lastNames,counter);

emailList = Arrays.copyOf(emailList, counter);

ageList = Arrays.copyOf(ageList, counter);

imgLoc = Arrays.copyOf(imgLoc, counter);

data = Arrays.copyOf(data, counter);

for (int i = 0; i <= counter - 1; i++){

data[i] = firstNames[i] + " " + lastNames[i] + ", " + ageList[i];

}

ArrayList arrays = new ArrayList();

arrays.add(firstNames);

arrays.add(lastNames);

arrays.add(emailList);

arrays.add(ageList);

arrays.add(imgLoc);

arrays.add(data);

return arrays;

}

使用ArrayList是个猜测.我不确定我是否朝着正确的方向前进.

解决方法:

我认为这是一个糟糕的主意.

我更喜欢一个将first,last,email,age和image封装到Person类中的对象,并返回一个List.

Java是一种面向对象的语言.如果你不再考虑像字符串,整数和数组这样的原语,并开始考虑对象,你会做得更好.只要有可能,就可以将要组合在一起的东西封装成一个对象.

这是我写这个方法的方法:

public List readPersons(File file) throws FileNotFoundException {

List persons = new LinkedList();

Scanner f = new Scanner(file).useDelimiter(",");

while (f.hasNext()){

String first = f.next();

String last = f.next();

String email = f.next();

String age = f.next(); // age ought to be a positive integer

String imageLocation = f.nextLine();

persons.add(new Person(first, last, email, age, imageLocation));

}

return persons;

}

代码更少,更易于理解.

标签:java,arrays

来源: https://codeday.me/bug/20190721/1495133.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值