📜  arraylistof 对象 - Java (1)

📅  最后修改于: 2023-12-03 14:59:23.328000             🧑  作者: Mango

ArrayList of Objects in Java

In Java, an ArrayList is a resizable array implementation of the List interface. This means that ArrayLists are dynamic, which allows them to grow or shrink in size as needed.

One of the benefits of ArrayLists is that they can be used to store objects of any type, including custom object types that you define. Here is an example of how to create an ArrayList of objects in Java:

ArrayList<Object> myList = new ArrayList<Object>();

In this example, we create an ArrayList called myList that can store objects of any type due to the use of the generic type Object.

We can then add objects to this ArrayList by calling the add() method. For example:

myList.add("Hello");
myList.add(42);
myList.add(new MyClass());

In this example, we added a string, an integer, and a custom object called MyClass to our ArrayList.

We can also retrieve objects from an ArrayList by calling the get() method and passing in the index of the object we want to retrieve. For example:

Object obj = myList.get(0);

This would retrieve the first object in the ArrayList, which in this case is the string "Hello".

We can also remove objects from an ArrayList by calling the remove() method and passing in the object we want to remove. For example:

myList.remove("Hello");

This would remove the string "Hello" from the ArrayList.

In addition to these basic operations, there are many other methods available for working with ArrayLists in Java. Some examples include:

  • size(): Returns the number of objects in the ArrayList.
  • contains(): Returns true if the ArrayList contains a specific object.
  • clear(): Removes all objects from the ArrayList.

Overall, ArrayLists are a powerful tool for working with collections of objects in Java. They provide flexible and dynamic storage, can store objects of any type, and offer a range of useful methods for working with the data they contain.