Melvin Lai
Melvin Lai

Reputation: 901

What array to use to store an Object?

I never stored an object of Strings in a java array before. So I do not know how to do it. Are there more than 1 ways to store an object into an array?

Upvotes: 0

Views: 327

Answers (4)

Andreas Dolk
Andreas Dolk

Reputation: 114757

Assuming, you have something like this

public class MyClass {
  public String one;
  public String two;
  public String three;
  public String four;

  public MyClass(String one, String two, String three, String four) {
    this.one = one;
    this.two = two;
    this.three = three;
    this.four = four;
  }
}

the you can store an instance of that class in an array:

MyClass[] myClasses = {new MyClass("one", "two", "three", "four")};
System.out.println(myClasses[0].one);  // will print "one"

There are some different ways to create an array (of Strings) and to set values:

1.

String[] strings = new String[3];
strings[0] = "one";
strings[1] = "two";
strings[2] = "three";

2.

String[] strings = new String[]{"one", "two", "three"};

3.

String[] strings = {"one", "two", "three"};

Upvotes: 1

Bhaskar Reddy
Bhaskar Reddy

Reputation: 480

Better way to use List, it is a collection interface. we are not storing objects , we are storing references(Memory addresses) of the objects. and use generics concept give more performance.

   Ex:

List<String> references = new ArrayList<String>(); 
List<OurOwnClass> references = new ArrayList<OurOwnClass>();

Upvotes: 1

Vishesh Chandra
Vishesh Chandra

Reputation: 7071

This line of steps maybe helpful to you..

In case of Array you can store only one kind of data,

Object[] myObjectArray = Object[NumberOfObjects];
myObjectArray[0] = new Object();

If you are talking about the String object, then you can store your String object also.

String[] myStringArray = String[NumberOfObjects];
myStringArray[0] = new String();

or

String[] myStringArray = String[NumberOfObjects];
myStringArray[0] = "Your String";

Here you can store your string object of Sting without using new operator.

Upvotes: 2

5w4rley
5w4rley

Reputation: 363

Object[] myObjectArray=new Object[numberOfObjects];
myObjectArray[0]=objectToStore;

and so on

Upvotes: 0

Related Questions