Matt
Matt

Reputation: 57

How to create an Array with 2 Arrays inside of different types Java

I have 2 Arrays, one of String type and one of Int type. Is it possible to put both of these into another array?

Example for claification:

String[] grades = { A, B, C, D, E, F };
int[] marks = { 90, 80, 70, 60, 50 };

int[][] combined { grades, marks };

I need to be able to address each of them individually through the use of the combined array by typing combined[0][4] (to receive 'E') etc.

If this is possible, what would I use for my class return type? It is currently set to return int[][] but this doesn't work because a string can't be converted into an int.

My current theory is to have it return a string array and convert my integers to strings but this is inefficient and loses a lot of functionality, if anyone knows any smarter ways to do it I would love any advice.

Thank you for your time

Upvotes: 0

Views: 607

Answers (2)

Akash R
Akash R

Reputation: 129

Approach 1 : You could use a 2D object array.

int max = Math.max(grades.length,marks.length);

example :

Object[][] objArr = new Object[max][2];
objArr[0][0] = marks[0];
objArr[0][1] = grades[0];

The Array looks like {90,A}

to return a string you can get the grades and cast it to String

 return (String) obj[0][1];   // returns "A"

Approach 2 : You could use the ascii value for the grades and you can have them in 2D Integer array itself.

Integer[][] marksAndGrades = new Integer[max][2];
marksAndGrades[0][0] = marks[0];
marksAndGrades[0][1] = (int)grades[0].charAt(0);

Here the array looks like {90,65}

To return the grade based on the marks

return String.valueOf((char)(int)marksAndGrades[0][1]);   // returns "A"

Upvotes: 2

Jeroen Steenbeeke
Jeroen Steenbeeke

Reputation: 4048

You could achieve this by first changing your array of numbers from int[] to Integer[], and then changing the combined array to Object[][]:

String[] grades = { "A", "B", "C", "D", "E", "F" };
Integer[] marks = { 90, 80, 70, 60, 50 };

Object[][] combined = { grades, marks };

Upvotes: 1

Related Questions