adding multiple data to Object array at run time - java

How to set values for two dimension array of objects in java.
following is my for loop :
Object[][] hexgenSecurityInferenceData = null;
for (String methodName: knowGoodMap.keySet()) {
hexgenSecurityInferenceData = new Object[][] {
{
(KnownGoodInfoRO) knowGoodMap.get(methodName), new Object[] {
(MethodPropertiesRO) methodPropertiesMap.get(methodName), (List) methodParametersMap.get(methodName)
}
},
};
}
this prints only one row of data. I am sure that i make mistake when adding values to Array of Object but really don't know how to fix.
Kindly help me to fix this

You can't add elements to an array - you can only set elements in an array.
I suggest you have a List<Object[]> instead:
List<Object[]> hexgenSecurityInferenceData = new ArrayList<Object[]>();
for (String methodName:knowGoodMap.keySet()) {
hexgenSecurityInferenceData.add(new Object[] {
knowGoodMap.get(methodName),
new Object[] {
methodPropertiesMap.get(methodName),
methodParametersMap.get(methodName)
}
});
}
(I've removed the casts as they were pointless... you're storing the values in an Object[] anyway. The only benefit of the casts would be to cause an exception if the objects were of an unexpected type.)
You could still use an array if you really wanted, but you'd need to create it with the right size to start with, and then keep the "current index". It's then generally harder to use arrays than lists anyway.
If you really need an array, you can create one from the list:
Object[][] array = hexgenSecurityInferenceData.toArray(new Object[0][]);
Doing it in two stages this way will be simpler than directly populating an array up-front.
I'd actually suggest two further changes:
Don't just use Object[] for this... create a type to encapsulate this data. With your current approach, you've even got a nested Object[] within the Object[]... any code reading this data will be horrible.
Use entrySet() instead of keySet(), then you don't need to fetch the value by key

You have a matrix of objects Object[][] so if you want to populate this 2-d array you have to do something like:
Object[][] hexgenSecurityInferenceData=new Object[10][10];
for(int i=0; i<10;i++){
for(int j=0; j<10;j++){
hexgenSecurityInferenceData[i][j] = new Object();
}
}
But as well pointed by Jon its better to have your own implementation/encapsulation instead of using Object

Using List is the best way to resolve this. However still you can do using object[] by initializing array.
Object[][] hexgenSecurityInferenceData = new Object[knowGoodMap.keySet().size()][];
int i = 0;
for (String methodName : knowGoodMap.keySet())
{
hexgenSecurityInferenceData[i][0] = new Object[][]
{
{(KnownGoodInfoRO) knowGoodMap.get(methodName),
new Object[]{(MethodPropertiesRO) methodPropertiesMap.get(methodName), (List) methodParametersMap.get(methodName)}
}
};
i++;
}

Related

Convert list to array in Java [duplicate]

This question already has answers here:
Converting 'ArrayList<String> to 'String[]' in Java
(17 answers)
Closed 4 years ago.
How can I convert a List to an Array in Java?
Check the code below:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
I need to populate the array tiendas with the values of tiendasList.
Either:
Foo[] array = list.toArray(new Foo[0]);
or:
Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Update:
It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.
From JetBrains Intellij Idea inspection:
There are two styles to convert a collection to an array: either using
a pre-sized array (like c.toArray(new String[c.size()])) or
using an empty array (like c.toArray(new String[0]). In
older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call
was intrinsified, making the performance of the empty array version
the same and sometimes even better, compared to the pre-sized
version. Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the
size and toArray call which may result in extra nulls
at the end of the array, if the collection was concurrently shrunk
during the operation. This inspection allows to follow the
uniform style: either using an empty array (which is recommended in
modern Java) or using a pre-sized array (which might be faster in
older Java versions or non-HotSpot based JVMs).
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Since Java 11:
String[] strings = list.toArray(String[]::new);
I think this is the simplest way:
Foo[] array = list.toArray(new Foo[0]);
Best thing I came up without Java 8 was:
public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
if (list == null) {
return null;
}
T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
list.toArray(listAsArray);
return listAsArray;
}
If anyone has a better way to do this, please share :)
I came across this code snippet that solves it.
//Creating a sample ArrayList
List<Long> list = new ArrayList<Long>();
//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);
//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);
//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);
The conversion works as follows:
It creates a new Long array, with the size of the original list
It converts the original ArrayList to an array using the newly created one
It casts that array into a Long array (Long[]), which I appropriately named 'array'
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
For ArrayList the following works:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5
You can use toArray() api as follows,
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);
Values from the array are,
for(String value : stringList)
{
System.out.println(value);
}
This (Ondrej's answer):
Foo[] array = list.toArray(new Foo[0]);
Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.
Try this:
List list = new ArrayList();
list.add("Apple");
list.add("Banana");
Object[] ol = list.toArray();

int [] [] convert --to--> Vector<Vector<Double>>

I would like to convert an integer [] [] to a Vector<Vector<Double>>. After much reading, it seems no one has left a searchable post on the web for something of this nature. plenty of int vector to double vector, arraylist to vector, etc. Sadly I haven't found what i am looking for. So..Do any of you folks know an appropriate method for this? I was thinking of converting my int[][] to strings then convert that to vector<vector<Double>>. Opinions? Would something like this be useful, ie. converting my array to object array
Object[] a1d = { "Hello World", new Date(), Calendar.getInstance(), };
// Arrays.asList(Object[]) --> List
List l = Arrays.asList(a1d);
// Vector contstructor takes Collection
// List is a subclass of Collection
Vector v;
v = new Vector(l);
// Or, more simply:
v = new Vector(Arrays.asList(a1d));
Otherwise could you give me a better example that may have less steps? Thanks a Bunch again.
First of all: avoid Vector, it is obsolete; use ArrayList instead (or something simmilar).
Read more here
Secondly, if I had to convert a 2d array to a list of lists, I'd keep it very simple:
List<List<Double>> list = new ArrayList<ArrayList<Double>>();
for(int i=0; i<100; i++) //100 or whatever the size is..
{
List<Double> tmp = new ArrayList<Double>();
tmp = Arrays.asList( ... );
list.add( tmp );
}
I hope I understood your problem right.
Vector is an old class that is not deprecated but shouldn't be used anymore. Use ArrayList instead.
You should use the LIst interface rather than using the concrete Vector class. Program on interfaces, not on implementations.
Moreover, having repeating conversions like this shows a lack of design. Encapsulate your data into usable objects that don't need conversion each time you need a new functionality.
If you really need to do this: use loops:
int[][] array = ...;
List<List<Double>> outer = new Vector<List<Double>>();
for (int[] row : array) {
List<Double> inner = new Vector<Double>();
for (int i : row) {
inner.add(Double.valueOf(i));
}
outer.add(inner);
}
Transforming from int to STring and then from String to Double is wasteful.
A Vector is one dimensional.
You could have a Vector of Vectors to simulate a 2D array:
Vector v = new Vector();
for (int i = 0; i < 100; i++) {
v.add(new Vector());
}
//add something to a Vector
((Vector) v.get(50)).add("Hello, world!");
//get it again
String str = (String) ((Vector) v.get(50)).get(0);
Note: Vector is an old collection that is not recommended to be used

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

Working with a List of Lists in Java

I'm trying to read a CSV file into a list of lists (of strings), pass it around for getting some data from a database, build a new list of lists of new data, then pass that list of lists so it can be written to a new CSV file. I've looked all over, and I can't seem to find an example on how to do it.
I'd rather not use simple arrays since the files will vary in size and I won't know what to use for the dimensions of the arrays. I have no issues dealing with the files. I'm just not sure how to deal with the list of lists.
Most of the examples I've found will create multi-dimensional arrays or perform actions inside the loop that's reading the data from the file. I know I can do that, but I want to write object-oriented code. If you could provide some example code or point me to a reference, that would be great.
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> singleList = new ArrayList<String>();
singleList.add("hello");
singleList.add("world");
listOLists.add(singleList);
ArrayList<String> anotherList = new ArrayList<String>();
anotherList.add("this is another list");
listOLists.add(anotherList);
Here's an example that reads a list of CSV strings into a list of lists and then loops through that list of lists and prints the CSV strings back out to the console.
import java.util.ArrayList;
import java.util.List;
public class ListExample
{
public static void main(final String[] args)
{
//sample CSV strings...pretend they came from a file
String[] csvStrings = new String[] {
"abc,def,ghi,jkl,mno",
"pqr,stu,vwx,yz",
"123,345,678,90"
};
List<List<String>> csvList = new ArrayList<List<String>>();
//pretend you're looping through lines in a file here
for(String line : csvStrings)
{
String[] linePieces = line.split(",");
List<String> csvPieces = new ArrayList<String>(linePieces.length);
for(String piece : linePieces)
{
csvPieces.add(piece);
}
csvList.add(csvPieces);
}
//write the CSV back out to the console
for(List<String> csv : csvList)
{
//dumb logic to place the commas correctly
if(!csv.isEmpty())
{
System.out.print(csv.get(0));
for(int i=1; i < csv.size(); i++)
{
System.out.print("," + csv.get(i));
}
}
System.out.print("\n");
}
}
}
Pretty straightforward I think. Just a couple points to notice:
I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List<String>.
In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:
List<List<String>> csvList = new ArrayList<List<String>>(500);
That way you would never waste processing time waiting for your list to grow dynamically grow. This is why I pass "linePieces.length" to the constructor. Not usually a big deal, but helpful sometimes.
Hope that helps!
If you are really like to know that handle CSV files perfectly in Java, it's not good to try to implement CSV reader/writer by yourself. Check below out.
http://opencsv.sourceforge.net/
When your CSV document includes double-quotes or newlines, you will face difficulties.
To learn object-oriented approach at first, seeing other implementation (by Java) will help you. And I think it's not good way to manage one row in a List. CSV doesn't allow you to have difference column size.
The example provided by #tster shows how to create a list of list. I will provide an example for iterating over such a list.
Iterator<List<String>> iter = listOlist.iterator();
while(iter.hasNext()){
Iterator<String> siter = iter.next().iterator();
while(siter.hasNext()){
String s = siter.next();
System.out.println(s);
}
}
Something like this would work for reading:
String filename = "something.csv";
BufferedReader input = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try
{
input = new BufferedReader(new FileReader(filename));
String line = null;
while (( line = input.readLine()) != null)
{
String[] data = line.split(",");
csvData.add(Arrays.toList(data));
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if(input != null)
{
input.close();
}
}
I'd second what xrath said - you're better off using an existing library to handle reading / writing CSV.
If you do plan on rolling your own framework, I'd also suggest not using List<List<String>> as your implementation - you'd probably be better off implementing CSVDocument and CSVRow classes (that may internally uses a List<CSVRow> or List<String> respectively), though for users, only expose an immutable List or an array.
Simply using List<List<String>> leaves too many unchecked edge cases and relying on implementation details - like, are headers stored separately from the data? or are they in the first row of the List<List<String>>? What if I want to access data by column header from the row rather than by index?
what happens when you call things like :
// reads CSV data, 5 rows, 5 columns
List<List<String>> csvData = readCSVData();
csvData.get(1).add("extraDataAfterColumn");
// now row 1 has a value in (nonexistant) column 6
csvData.get(2).remove(3);
// values in columns 4 and 5 moved to columns 3 and 4,
// attempting to access column 5 now throws an IndexOutOfBoundsException.
You could attempt to validate all this when writing out the CSV file, and this may work in some cases... but in others, you'll be alerting the user of an exception far away from where the erroneous change was made, resulting in difficult debugging.
public class TEst {
public static void main(String[] args) {
List<Integer> ls=new ArrayList<>();
ls.add(1);
ls.add(2);
List<Integer> ls1=new ArrayList<>();
ls1.add(3);
ls1.add(4);
List<List<Integer>> ls2=new ArrayList<>();
ls2.add(ls);
ls2.add(ls1);
List<List<List<Integer>>> ls3=new ArrayList<>();
ls3.add(ls2);
methodRecursion(ls3);
}
private static void methodRecursion(List ls3) {
for(Object ls4:ls3)
{
if(ls4 instanceof List)
{
methodRecursion((List)ls4);
}else {
System.out.print(ls4);
}
}
}
}
Also this is an example of how to print List of List using advanced for loop:
public static void main(String[] args){
int[] a={1,3, 7, 8, 3, 9, 2, 4, 10};
List<List<Integer>> triplets;
triplets=sumOfThreeNaive(a, 13);
for (List<Integer> list : triplets){
for (int triplet: list){
System.out.print(triplet+" ");
}
System.out.println();
}
}

How to convert object array to string array in Java

I use the following code to convert an Object array to a String array :
Object Object_Array[]=new Object[100];
// ... get values in the Object_Array
String String_Array[]=new String[Object_Array.length];
for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString();
But I wonder if there is another way to do this, something like :
String_Array=(String[])Object_Array;
But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
What's the correct way to do it ?
Another alternative to System.arraycopy:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);
System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:
Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.
First, let's see what Oracle has to say
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?
List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();
Probably, many of you would think that this code is doing the same, but it does not.
Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;
When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!
Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;
So tList.toArray is instantiating a Objects and not Strings...
Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following
String tArray[] = tList.toArray(new String[0]);
Hope it is clear enough.
The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:
Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
String apply(Object from){
return from.toString();
}
});
This take you away from using arrays,but I think this would be my prefered way.
This one is nice, but doesn't work as mmyers noticed, because of the square brackets:
Arrays.toString(objectArray).split(",")
This one is ugly but works:
Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")
If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.
If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.
If you know your Object array contains Strings only, you may also do (instread of calling toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:
Object[] o = new String[10];
String[] s = (String[]) o;
You can use type-converter.
To convert an array of any types to array of strings you can register your own converter:
TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {
#Override
public String[] convert(Object[] source) {
String[] strings = new String[source.length];
for(int i = 0; i < source.length ; i++) {
strings[i] = source[i].toString();
}
return strings;
}
});
and use it
Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
String[] strings = TypeConverter.convert(objects, String[].class);
For your idea, actually you are approaching the success, but if you do like this should be fine:
for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];
BTW, using the Arrays utility method is quite good and make the code elegant.
Object arr3[]=list1.toArray();
String common[]=new String[arr3.length];
for (int i=0;i<arr3.length;i++)
{
common[i]=(String)arr3[i];
}
Easily change without any headche
Convert any object array to string array
Object drivex[] = {1,2};
for(int i=0; i<drive.length ; i++)
{
Str[i]= drivex[i].toString();
System.out.println(Str[i]);
}

Categories