I need to store different objects in the ArrayList. Objects are similar in nature but different and have different methods.
Circle c = new Circle();
Cube s =
This is what you have to do.
Define a Shape interface..
Implement the interface for Circle and Cube
Create shape objects for Circle and Cube and add these to arraylist..
Code below:
public interface Shape {
public void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
public class Cube implements Shape {
@Override
public void draw() {
System.out.println("Drawing Cube");
}
}
public class Simulator{
public static void main(String[] s){
Shape s1 = new Circle();
Shape s2 = new Cube();
ArrayList<Shape> shapeList = new ArrayList<Shape>();
shapeList.add(s1);
shapeList.add(s2);
}
}
ArrayList<Object> list = new ArrayList<Object>();
you can call the all methods including Object class method.
List<Object> list = new ArrayList<>();
list.add(new ArrayList<>());
list.add(Integer.valueOf("24"));
list.add(Long.valueOf("25"));
list.add("STRING");
list.add(new Object());
System.out.println(Arrays.toString(list.toArray()));
//Console print: " [[], 24, 25, STRING, java.lang.Object@4554617c] "
You may store any object type.
You can just create an ArrayList<Object>
. That's a list that can store anything. It's not very useful to work with, because taking things out basically forces you to check their type in order to call any methods. For that reason you should almost always avoid doing this.
Objects in collections usually have something in common - if they don't, you should rethink why you're throwing them into the same collection. In your case, they're all shapes. So instead, consider adding a shared interface such as Shape
which combines the common functionality.
I'm simplifying slightly because you have the concept of both 2D and 3D shapes, but here's the gist:
interface Shape
{
double area();
double perimeter();
}
class Circle implements Shape
{
// ...
public double area()
{
return radius * radius * Math.PI;
}
public double perimeter()
{
return 2 * Math.PI * radius;
}
}
class Square implements Shape
{
//...
}
And then creating a list of Shape
s:
List<Shape> shapes = Arrays.asList(new Circle(3), new Square(4), ...);
i think you can create a list of objects, and when use someone u cast to the specific type
List<Object> obj = new ArrayList<Object>();
if (obj.get(i) instanceof Class) {
Class objCast = (Class)obj
}
Objects DOC