Hi,

I wanted to know how I can add data to an ArrayList if the collection is not: Private ArrayList<String> files; and instead: Private ArrayList<People> files. Would the code look like this:

   public void addPerson(String name){

    files.add(name);

    }

or:

public void addPerson(String name) {

People people; // Declare an object
people = new People(name);  // Create an object

files.add(people);

}

Dani AI

Generated

Core point: an ArrayList<T> only accepts instances of T (or subclasses). Since the field is declared to hold People/Person objects, passing a raw String will produce a compile-time type error. was correct about generics enforcing this, and ’s first attempt fails for that reason.

Prefer declaring and initializing the collection via the List interface and validate input before adding. Example pattern (uses a singular class name Person and a simple validation step):

private List<Person> files = new ArrayList<>();

public boolean addPersonByName(String name) {
    if (name == null || name.trim().isEmpty()) return false;
    Person person = new Person(name);
    return files.add(person);
}

A minimal Person class makes the constructor and stored data explicit:

public class Person {
    private final String name;
    public Person(String name) { this.name = name; }
    public String getName() { return name; }
    @Override public String toString() { return name; }
}

Troubleshooting and best-practices (ties to prior replies): ’s suggestion to add a Person object is on track — either pass a Person into the add method or construct one from a name before adding. Ensure the field is actually initialized (otherwise a NullPointerException occurs). Use private (lowercase) for visibility, prefer singular class names (Person not People), and implement equals/hashCode if the list will be searched or deduplicated. If storing plain names is the goal, change the collection to hold String instead of Person.

Recommended Answers

All 8 Replies

Does the code compile without errors? The intent of generics was to allow the compiler to check if the correct data types are being added to the ArrayList.

The first code line doesn't work.

Is your question answered now?

No, not really.

Please explain what your problem is.
Ask some specific questions about what you are trying to do.

In above question do you want to add name in people object? instead of string?
please explain your question further.

It would probably llok like this:

 public void addPerson(Person p){
    files.add(p);
 }

As james said it is right.just go and try with this.

also mark this question as solved,if your doubt is cleared.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.