Multiple type array - java

I am working with an array and need some help. I would like to create an array where the first field is a String type and the second field is an Integer type.
For result:
Console out
a 1
b 2
c 3

An array can only have a single type.
You can create a new class like:
Class Foo{
String f1;
Integer f2;
}
Foo[] array=new Foo[10];
You might also be interested in using a map (it seems to me like you're trying to map strings to ids).
EDIT:
You could also define your array of type Object but that's something i'd usually avoid.

You could create an array of type object and then when you print to the console you invoke the toString() of each element.
Object[] obj = new Object[]{"a", 1, "b", 2, "c", 3};
for (int i = 0; i < obj.length; i++)
{
System.out.print(obj[i].toString() + " ");
}
Will yield:
a 1 b 2 c 3

Object[] randArray = new Object [3];
randArray[0] = new Integer(5);
randArray[1] = "Five";
randArray[2] = new Double(5.0);
for(Object obj : randArray) {
System.out.println(obj.toString());
}
Is this what you're looking for?

Object[] myArray = new Object[]{"a", 1, "b", 2 ,"c" , 3};
for (Object element : myArray) {
System.out.println(element);
}

Object [] field = new Object[6];
field[0] = "a";
field[1] = 1;
field[2] = "b";
field[3] = 2;
field[4] = "c";
field[5] = 3;
for (Object o: field)
System.out.print(o);

try using Vector instead of Array.

Related

Retrieving items from Collection

I have a Collection c, which contains 3 items. I want to assign these 3 items to 3 different variables
Collection<Object> c;
var1 = firstItem;
var2 = secondItem;
var3 = thirdItem;
How can I extract the elements of the collection?
You can do it as following:
Collection<Object> collection = ...;
Iterator iterator = collection.iterator();
Object firstItem = iterator.next();
Object secondItem = iterator.next();
Object thirdItem = iterator.next();
Update:
This option is fine only if you are sure that collection contains at least 3 items. Otherwise, you need to check whether iterator has next item (method hasNext) before calling next.
Maybe this can help you :
Object[] array = c.toArray();
Object var1 = array[0];
Object var2 = array[1];
Object var3 = array[2];
Note toArray() return an array of Object so in case of another Type you have to cast the result for example or you can use :
Collection<String> c = Arrays.asList("a", "b", "c");
String[] array = c.toArray(new String[c.size()]);
String var1 = array[0];
String var2 = array[1];
String var3 = array[2];
Or with a List
Collection<String> c = Arrays.asList("a", "b", "c");
List<String> list = (List<String>) c;
String var1 = list.get(0);
String var2 = list.get(1);
String var3 = list.get(2);

How do I convert List<List<Object>> to a multi-dimensional array?

List<List<Object>> EventAll = new ArrayList<List<Object>>();
while(rs1.next())
{
List<Object> row = new ArrayList<Object>();
/*EventAll.add(rs1.getRow(), row);*/
row.add(rs1.getString("eventName"));
row.add(rs1.getString("duration"));
row.add(rs1.getString("playhead"));
EventAll.add(row);
}
String[][] stringArray = EventAll.toArray(new String[EventAll.size()][]);//line 66
In the above example as you can see I have List<List<Object>> and I am adding column values to it in the while loop. It worked fine for me at this point.
But when I tried converting it into multi-dimensional array using toArray() method I am getting the following exception:
****EXCEPTION:**java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.ArrayList.toArray(Unknown Source)
at DataFromMySql.main(DataFromMySql.java:66)**
Object[][] array = new Object[EventAll.size()][];
int i = 0;
for (List<Object> event : EventAll) {//each list
array[i++] = event.toArray(new Object[event.size()]);
}
toArray can convert your List<List<String>> (you should, BTW, change your List<List<Object>> to List<List<String>>) to List<String>[], not to a String[][].
It can also convert each inner List<String> to a String[].
Therefore, you'll have to create the 2-D array, and initialize each row of that array separately with EventAll.get(i).toArray(new String[EventAll.get(i).size()]).
Please note that this will only work if your inner Lists do have the same length and all Objects are strings!
String[][] array = new String[list.size()][list.get(0).size()];
System.out.println();
int i = 0;
for (List<Object> l : list ) {
int j = 0;
for (Object obj : l) {
array[i][j] = (String) obj;
j++;
}
i++;
}

adding String array into ArrayList

I want to append a and b string arrays to arrayList. But "1.0" have to be "1" using with split. Split method returns String[] so arrayList add method does not work like this.
Can you suggest any other way to doing this ?
String[] a = {"1.0", "2", "3"};
String[] b = {"2.3", "1.0","1"};
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(a[0].split("."));
arrayList.add(a[0].split("\\.")[0]);
Should be as below
arrayList.add(a[0].split("\\.")[0]);
Split method returns an array. You have to access to his position to get the number.
arrayList.add(a[0].split("\\.")[0]);
You can also use substring method:
arrayList.add(a[0].substring(0, 1));
Access first element of that array like this :
for (int i = 0; i < a.length; i++) {
if (a[i].contains("."))
arrayList.add(a[i].split("\\.")[0]);
else
arrayList.add(a[i]);
}
Why split it?. Just use a replaceAll(), it will be more efficient as it won't create an array of Strings.
public static void main(String[] args) {
String[] a = { "1.7", "2", "3" };
List<String> arrayList = new ArrayList<String>();
for (int i = 0; i < a.length; i++) {
arrayList.add(a[i].replaceFirst("\\..*", "")); // escape the . (match it as a literal), then followed by anything any number of times.
}
System.out.println(arrayList);
}
O/P :
[1, 2, 3]
If you use Java 8,
String[] a = {"1.0", "2", "3"};
List<String> list = Arrays.stream(a).map(s -> s.split("\\.")[0]).collect(Collectors.toList());
// OR
List<String> list2 = Arrays.stream(a).map(s -> {
int dotIndex = s.indexOf(".");
return dotIndex < 0 ? s : s.substring(0, dotIndex);
}).collect(Collectors.toList());
This is working properly for me: arrayList.add(a[0].split("\\.")[0]);

Merging two lists into a new list, index to same index, while not adding to length

Im trying to merge two lists into a new list with all the values of the two staying at the same index as the originals, while not adding to the new list length.
List A contains one number at random indexes, some are null, numbers are between 1-3.
List B contains numbers 123 on all indexes.
I tried using a for loop and list add, but then it gave me a indexoutofbounds because it seems that list add pushes the content of the list when it adds a value. Im now trying to use hashmap:
lists:
Int arraylength = 10;
ArrayList<Integer> mergeballs = new ArrayList<>(arraylength); // merging list A
// contenent: null,3,null,null,2,3,null,1,null,2
ArrayList<Integer> hats = new ArrayList<>(arraylength); // merging list B
//contenent: 123,123,123,123,123,123,123,123,123,123
ArrayList<Integer> hatsMerged = new ArrayList<Integer>(arraylength); // A & B merged
for (int o = 0; o < stickarray.length; o++) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer (arraylength);
map.put(o, hats.get(o) + mergeballs.get(o));
hatsMerged.add(o,map.get(o));
System.out.print(hatsMerged.get(o));
}
With this code im also getting a index out of bounds and hats and mergeballs are getting summarized, which I do not want. I want it to be: 123,1233,123,123,1232,1233,123,1231,123,1232
How can I do this? and is hashmap the best option?
Here is one approach to do what you seem to be asking for. Ignore null, convert the int to a String - then concatenate the other int to the String and convert back to an int for storage in the merged List<Integer>. Something like,
public static List<Integer> merge(List<Integer> a, List<Integer> b) {
List<Integer> al = new ArrayList<>();
for (int i = 0; i < a.size(); i++) {
Integer val = a.get(i);
StringBuilder sb = new StringBuilder();
if (val != null) {
sb.append(val);
}
Integer bv = b.get(i);
if (bv != null) {
sb.append(bv);
}
try {
al.add(Integer.parseInt(sb.toString()));
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
}
return al;
}
public static void main(String[] args) {
List<Integer> a = Arrays.asList(123, 123, 123, 123, 123, 123, 123, 123,
123, 123);
List<Integer> b = Arrays.asList(null, 3, null, null, 2, 3, null, 1,
null, 2);
List<Integer> merged = merge(a, b);
System.out.println(merged);
}
Output is (the requested) -
[123, 1233, 123, 123, 1232, 1233, 123, 1231, 123, 1232]
You need not use a hashmap . You can just check for the null value and substitute with zero and add and hence merge the values between the two lists. You can avoid 2 get calls by assigning mergeballs.get(0) to an Integer local variable and use it in the conditional expression.
Integer result;
ArrayList<Integer> hatsMerged = new ArrayList<Integer>(arraylength); // A & B merged
for (int o = 0; o < arraylength; o++) {
result = ((mergeballs.get(o) == null) ? 0 : mergeballs.get(o)) + ((hats.get(o) == null) ? 0 : hats.get(o));
hatsMerged.add(result);
System.out.print(hatsMerged.get(o));
}

Array structure in java

Can I create an array like this in java???
Array
([0]
array
[items1] = "one"
[items2] = "two"
[items3] = "three")
([1]
array
[items1] = "one###"
[items2] = "two###"
[items3] = "three#")
Thanx for your help
Yes, you can do this by creating an array of arrays. For example:
String[][] twoDimensionalPrimitiveArray = {
{"one", "two", "three"},
{"one###", "two###", "three###"}
};
You can also do this with the collection types:
List<List<String>> listOfLists = new ArrayList<>();
listOfLists.add(createList("one", "two", "three"));
listOfLists.add(createList("one###", "two###", "three###"));
// ...
private static List<String> createList(String... values) {
List<String> result = new ArrayList<>();
for (String value : values) {
result.add(value);
}
return result;
}
Edit
#immibis has rightly pointed out in the comments that createList() can be written more simply as new ArrayList(Arrays.asList(values)).
Yes, you can define an array of arrays:
String[][] arrayOfArrays = new String[2][]; // declare and initialize array of arrays
arrayOfArrays[0] = new String[3]; // initialize first array
arrayOfArrays[1] = new String[3]; // initialize second array
// fill arrays
arrayOfArrays[0][0] = "one";
arrayOfArrays[0][1] = "two";
arrayOfArrays[0][2] = "three";
arrayOfArrays[1][0] = "one###";
arrayOfArrays[1][1] = "two###";
arrayOfArrays[1][2] = "three#";
And to test it (print values):
for (String[] array : arrayOfArrays) {
for (String s : array) {
System.out.print(s);
}
System.out.println();
}
For two dimension arrays in Java you can create them as follows:
// Example 1:
String array[][] = {"one", "two", "three"},{"one###", "two###", "three###"}};
Alternatively you can define the array and then fill in each element but that is more tedious, however that may suit your needs more.
// Example 2:
String array[][] = new String[2][3];
array[0][0] = "one";
array[0][1] = "two";
array[0][2] = "three";
array[1][0] = "one###";
array[1][1] = "two###";
array[1][2] = "three#";
String[] twoDArray[] = {{"one", "two", "three"}, {"one###", "two###", "three###"}};

Categories

Resources