0

Consider the following code,

import java.util.ArrayList;
public class UselessCode {
public static void main(String args[]){

    ArrayList<Integer> x = new ArrayList<Integer>();
        x.add(81);
        x.add(53);
        x.add(27);

            for(int i=0; i < Data.size(); ++i)
            {
                System.out.println(x.get(i));
            }
        }
    }

The output of the code above prints out the three numbers I have added to the array as expected.

Is there a way to modify the code so it adds a persons name to each number?

For example, the output would the be ("Mark", 81), ("Scot", 53) and so on.

2
  • 1
    You need HashMap Commented Feb 15, 2014 at 12:08
  • 2
    You probably need a list of Person objects, each Person having a name field and a number field. Instead of ArrayList<Integer>, you would thus have an ArrayList<Person>. Commented Feb 15, 2014 at 12:10

3 Answers 3

3

First of all: you're looking at ArrayLists, not arrays.

And yes, that's possible. This is when you create your own class that holds these two fields.

class Person {
    private int age; // Or make it a date object
    private String name;

    // Constructor
    // Getters
}

After which you simply have a list of Person objects:

List<Person> people = new ArrayList<>();
people.add(new Person("John", 21));

You should read through this tutorial for a good overview.

Sidenote: you can't have spaces in your class name. I also suggest you follow the Java Naming Conventions by starting the classname with an uppercase character (and by making it descriptive).

Another possibility is using a HashMap<String, Integer> but I feel like a custom class is more warranted here.

There are quite a bit of links in this post, I suggest you read through them all since these are elementary concepts that all your programs will depend on.

Sign up to request clarification or add additional context in comments.

Comments

2

ArrayList<Integer> is set to store only Integer values, if you need to add another items, I would suggest that you consider creating your own class, such as Person, that would contain both number and name.

class Person {

public int number;
public String name;

}

and then you can make an ArrayList<Person>, that contains the whole object and access its individual fields like this:

System.out.println("Id of the person %d", list.get(i).number);
System.out.println("Name of the person %s", list.get(i).name);

Comments

0

you need to use map instead of array , or create a class for name and number and to the array but now you add objects instead of integeres

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.