Question:
java array?
Mr.Me
2007-12-03 11:17:34 UTC
in java how would I create an array , where each object stores an integer and a string, without calling on another class.

so it would sort of look like student[i] = ("dan", 1542)
that is made and used in one method
Four answers:
2007-12-03 21:44:19 UTC
You can create a 2 dimentional array, of type String. The first part of the array is already a String, the second part is an int. Java uses boxing and when you add an int to the array it will convert it to a String. When you go to access the array simply convert the second part to an int (Integer.parseint(param)).



This is not the 'best' way to do it. A better way would to use 2 arrays.



I just thought of another way to do this. You could have an array of type Object (again not the prettiest way).
2007-12-03 19:40:26 UTC
I don't think you can have a 2 dimensional array that stores different data types. In the past, what I have done in situations like this, is simply create 2 separate arrays that reference each other. So, whenever you add a name to your string array at position 1 [0], you add the corresponding number to your int array at the same index [0]. Although it sounds shaky, if you think about it, the logic is basically almost identical to the method you would use to add the values to a 2 dimensional array. If you do it in a loop, using the counter as the index (or something similar) you are pretty much gauranteed that the values will correspond. Good luck.

EDIT : after looking at your Q further, it looks like what you are really looking for is an array of objects (or an arraylist), in which case you would assign properties to the object, then assign the object to the array, like so :



student1.Name = "Fred"

student1.Id = 5045



studentArray[0] = student1



.. where studentArray is an array of students ( student [ ] ).
macharoni
2007-12-03 20:04:47 UTC
Make a class, like Student:



public class Student

{

 public String name; // Better encapsulation if these are private

 public int num;

 Student(String newname, int newnum) { name=newname; num = newnum; } // Constructor

 Student() {} // Fill in for default constructor

}



Then make an array of that class:



Student[] arr = new Student[10];

arr[0] = new Student("dan", 1542);

arr[1] = new Student("fred", 1939);

...
2007-12-03 19:56:22 UTC
An array can only be of one data type, so you could not do this. You could just use parallel arrays as an alternative.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...