Raggaer
Raggaer

Reputation: 3318

Java list items

Im using the following code

List<String> text = new ArrayList<String>();
text.add("Hello");

So that list will only accept Strings to be added, how can I add into one list more types of variables like ints and strings together like

Adding into the text list some rectangle values like

rectangle name, rectangle width, rectangle height

So later I can access them in a loop

Upvotes: 5

Views: 1661

Answers (4)

rajah9
rajah9

Reputation: 12339

Expanding a bit on Duncan's answer, here is how you might create a Rectangle class:

public class Rectangle {
    private String name;
    private int height;
    private int width;

    /** 
     * Create a rectangle by calling 
     *   Rectangle myRect = new Rectangle("foo", 20, 10);
     */
    public Rectangle(String name, int height, int width) {
        this.name = name;
        this.height = height;
        this.width = width;
    }
}

You would need to add accessor methods to it, so that you can retrieve the name, width, and height. These are usually public methods that are named things like getName and getWidth (nicknamed getters). You might also have a function that returns the area. Here's an example.

public String getName() { return name; } 
public int getHeight() { return height; } 
public int getWidth() { return width; } 

public String area() {
    int area = height * width;
    return "Rectangle " + name + " has an area " + area + ".";
}

Upvotes: 4

lazarusL
lazarusL

Reputation: 236

While the answer to create a class is certainly a better way to organize your program, the answer to your question is to create a list of type Object. Then you can add items to your list of any type. To determine which type you are dealing with at run time, you can use the instanceof keyword. But to be perfectly clear, this is not good practice.

List<Object> text = new ArrayList<String>();
text.add("Hello");
text.add(new Integer(10));

Upvotes: 0

gEdringer
gEdringer

Reputation: 16583

You can simply create a class which will contain the variables you need, and use that class as the data type in the listdeclaration.

e.g.:

class MyStructure{
  int anInteger;
  double aDouble;
  string aString;
  //Followed by any other data types you need.   

  //You create a constructor to initialize those variables.
  public MyStructure(int inInt, double inDouble, string inString){
     anInteger = inInt;
     aDouble = inDouble;
     aString = inString;
  }
}

Then when you have your main or your method, and declare a list you simply write:

List<MyStructure> myList = new ArrayList<>();
myList.add(new MyStructure(5, 2.5, "Hello!"));

Upvotes: 2

Duncan Jones
Duncan Jones

Reputation: 69339

Create your own Rectangle class and store those values in it.

List<Rectangle> rectangles = new ArrayList<>();
rectangles.add(new Rectangle("Foo", 20, 30));

Upvotes: 11

Related Questions