I dont know how to do this. But what i want is to create a two array.. one for the array class then the other is for the information that i will use for the selected class using for loop. I prefer for loop that for each loop.. ^_^.. My question is. Is it posible to create an array in which it will store an array too? for example:
private final Class<?>[] cls = {class1,class2,class3};
private final String[] myFirstArray = {array1[],array2[],array[]3};
private final String selectedarray[];
for(int i=0;i<cls.lenght();i++){
if(myArrayClassParameter == cls[i]){
selectedArray[] = myFirstArray[i];
}
}
Like that?
Well If it is posible my work will be less time consuming.. thanks.
Absolutely - you can create arrays of arrays, or even arrays of arrays of arrays, and so on. All you need is to add more pairs of square brackets [].
private final String[][] firstArray = new String[][] {
new String[] {"quick", "brown", "fox"}
, new String[] {"jumps", "over", "the"}
, new String[] {"lazy", "dog", "!"}
};
String[] selectedArray = firstArray[1];
Yes. These are called multidimensional arrays. Try them out and mess around with them. You'll learn better that way.
You must declare them like this:
Type[] smallerArray1;
Type[] smallerArray2;
Type[] smallerArray3;
Type[][] biggerArray = new Type[][]{smallerArray1, smallerArray2, smallerArray3};
Then you can use them like regular arrays.
Related
So I have two Arraylists bBag representing a bigBag and sbag1 and sbag2 representing smaller bags. sbag1 and sbag2 are Arraylist containing String[] and both of them are inside bBag.
import java.util.ArrayList;
import java.util.*;
public class Arraylist1 {
public static void main(String[] args) {
ArrayList<ArrayList<String[]>> bBag = new ArrayList<ArrayList<String[]>>();
ArrayList<String[]> sbag1 = new ArrayList<String[]>();
ArrayList<String[]> sbag2 = new ArrayList<String[]>();
String[] s1 = {"this", "is" , "Java", "bruh"};
String[] s2 = {"It", "rained"};
sbag1.add(s1);
sbag1.add(s2);
String[] s3 = {"today", "is", "20"};
sbag2.add(s3);
bBag.add(sbag1);
bBag.add(sbag2);
}
I want to modify sbag2's 1st string (i.e Today) to 'Tomorrow'such that it gets replaced in the bBag as well. Also how do i display it? thanks.
Strings are immutable, so you cannot directly modify it, you must replace it with a new string. Your containers, arrays and arraylist, hold references to objects in memory, not copies of object data. So, if you change the array, that change will be visible to any arraylist holding the array, and arraylist holding that arraylist, etc.
Only way is to traverse from bBag to bBag1 to s3 and update it. Do the same traversal to display from bBag.
This might work, but you need to replace the String with the new one.
public void modify(int bag, int sbag, Integer pos, String replacement){
//with bag being 1 or 2
//with sbag being 1 or 2
bBag.get(bag-1).get(sbag-1)[pos]= replacement;
}
So lets say I want to make an array of nine country names. I have the code to create the array:
String[] countryName = new String[9];
Lets say I wanted to add nine unique country names to this array. I could do something like this:
countryName[0] = "Mexico";
countryName[1] = "United States";
and so on. But is there a way I could add all of the names at once? Maybe something like an add() statement?
you can initialize the array with:
String[] countryName = new String[]{"Mexico", "Italy", "Spain"};
You can write simple utility method using varargs
static void addAll(String[] arr, String ... elements)
{
if (elements != null)
{
System.arraycopy(elements, 0, arr, 0, elements.length);
}
}
Usage
addAll(countryName, "Mexico", "US", "Ukraine");
Use an ArrayList this has the Add method.
ArrayList<String> countryName = new ArrayList<String>();
countryName.add("Mexico");
countryName.add("United States");
countryName.add("Dominican Republic");
countryName.add("...");
Enlist all contries in String and use split
String str="Country1,Country2,Country3";
String array[]=str.split(",");//You even don't need to initialize array
Use delimeter carefully to avoid extra spaces.
NOTE:
As this is one of the ways to add values to array but still I suggest you to go for Michel Foucault's answer as split will have more overhead than direct initialization.
Is it possible to have an array containing names or reference to other arrays?
e.g.
String[] fruits={"orange","apple"};
String[] colors={"red","blue","green"};
And the 3rd array String[] array1={"fruits","colors"};
I actually have many arrays and based on the array passed I need to compare it with the array already present.
Like if I pass a fruit array then compare array1[0]th array i.e fruits array to the passed array?
I can compare the passed array to individual arrays and perform comparison for each but is there a shorter way?
Like suggested in my comment below the question, you can use a map:
String[] fruits = {"orange", "apple"};
String[] colors = {"red", "blue", "green"};
Map<String, String[]> map = new HashMap<>();
map.put("fruits", fruits);
map.put("colors", colors);
String[] toCompare = map.get("fruits"); // will return the fruits array
You can have an array of arrays:
String[][] myArr = {fruits, colors};
But as #jlordo suggested, it's a better approach to have a Map that contains a String key which will represent the array's name, and the actual array as the value.
Since double array has already been presented as well as a map example lets see an example with arraylist.
String[] fruits = {"orange", "apple"};
String[] colors = {"red", "blue", "green"};
ArrayList<String[]> fruitsAndColors = new ArrayList<String[]>();
fruitsAndColors.add(fruits);
fruitsAndColors.add(colors);
You can read the java API for other insertion methods: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
You can have an array with references to almost anything using Object class (you are not limited to arrays of String):
Object [] myArr = {fruits, colors};
Given 3 variables (homeNumber,mobileNumber and workNumber), which can be null, but atleast one of those will be a String, I need to return a String array so I can use it later on an Android Dialog. I'm having troubles doing this. I tried doing it in an ArrayList and removing all null elements, which leaves an ArrayList with only Strings, like I want, but when trying to change it to an Array I get a ClassCast exception on the last line.
ArrayList numberList = new ArrayList();
numberList.add(homeNumber);
numberList.add(mobileNumber);
numberList.add(workNumber);
numberList.removeAll(Collections.singleton(null));
final String[] items= (String[]) numberList.toArray();
Any ideas how to fix this?
String[] items = new String[numberList.size()];
numberList.toArray(items);
You can do one of two things:
Pass in the type of array you want to get (there's no need to instantiate a full length array, performance is the same regardless):
final String[] items= (String[]) numberList.toArray(new String[0]);
However, the better solution is to use generics:
List<String> numberList = new ArrayList<String>();
final String[] items= (String[]) numberList.toArray();
The return type of ArrayList.toArray() is Object[], unless you pass an array as the first argument. In that case the return type has the same type as the passed array, and if the array is large enough it is used. Do this:
final String[] items= (String[])numberList.toArray(new String[3])
Use the other method toArray() of List class:
numberList.toArray(new String[numberList.size()]);
Change
ArrayList numberList = new ArrayList();
to
List<String> numberList = new ArrayList<String>();
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]);
}