Say that I wanted to return 6 arrays from one method to another (in another class). What is the best way of doing this and why?
This is what I have so far.
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<Object> arrays = new ArrayList<Object>();
arrays.add(firstNames);
arrays.add(lastNames);
arrays.add(emailList);
arrays.add(ageList);
arrays.add(imgLoc);
arrays.add(data);
return arrays;
}
Using an ArrayList was a guess. I'm not sure if I'm headed in the right direction there.
I think this is a terrible idea.
I'd prefer one object that encapsulates first, last, email, age, and image into a Person class and return a List of those.
Java's an object-oriented language. You'll do better if you stop thinking in terms of primitives like Strings, ints, and arrays and start thinking in terms of objects. Encapsulate things that are meant to be together into a single object whenever you can.
Here's how I'd write that method:
public List<Person> readPersons(File file) throws FileNotFoundException {
List<Person> persons = new LinkedList<Person>();
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;
}
Less code, and easier to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With