假设我想从一个方法返回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