Java arraylist object to array - java

I am creating an ArrayList of String Arrays in Java.. The code for the same is follows..
ArrayList<String[]> al = new ArrayList<String[]>();
for(int i = 0; i < t; i++) { // t is input by user representing size of arraylist
int k = sc.nextInt();
String[] s = new String[k]; // k string values input by user
}
Iterating to print the values of ArrayList
Iterator it = al.iterator();
while(it.hasNext()){
for(int i = 0; i < (it.next(new String[])).length; i++) { // error for dimension missing
System.out.println((it.next(new String[])).length); // error for dimension missing
}
}
I get an error of "array dimension missing" in the indicated lines. Please suggest how to convert ArrayList Object as String Array.

Try this
Iterator<String[]> it = al.iterator();
while(it.hasNext()){
String temp [] = it.next();
for(int i = 0; i < temp.length; i++) {
System.out.println(temp.length);
}
}

your new String[]
requires size, because you're making new array i.e
String[] myStringArray = new String[5];
also, your iteration to print values make no sense, try :
for(String[] stringArray: al) {
System.out.println("Size: " + stringArray.length);
for(String s: stringArray) {
System.out.println(s);
}
}

Related

creat empty array of strings

My app gets strings of images url from server and saves them in an array .the problem is number of images url is not constant so i want to create empty array of strings and its size determined according to input entered to it .
i used this Strings images=new Strings[5] and i want thing like that Strings images=new Strings[] so how i can do that this is part of my code
String[] images4=new String[3];
String[] images5=new String[3];
String[] images7=new String[3];
String[] images6=new String[3];
String[] images1=new String[3];
String[] images2=new String[3];
String[] images3=new String[3];
String[] totals=new String[3];
try {
JSONObject json = new JSONObject(Content);
JSONArray jre = json.getJSONArray("projects");
JSONArray jreimages = json.getJSONArray("screenshots");
mArrayList = new ArrayList<Projects>();
for (int j = 0; j < jre.length(); j++) {
mProduct = new Projects();
JSONObject jobject = jre.getJSONObject(j);
String name11 = jobject.getString("name");
String description = jobject.getString("description");
String status = jobject.getString("status");
String version = jobject.getString("version");
String id =jobject.getString("id");
mProduct.setyourText(name11);
mProduct.setyourstatu(status);
mProduct.setYourversion(version);
mProduct.setyourdescription(description);
int k=0;
int l=0;
int o=0;
int p=0;
int w=0;
for (int i = 0; i < jreimages.length(); i++) {
JSONObject jjobject = jreimages.getJSONObject(i);
String imageid=jjobject.getString("project_id");
if (imageid.equals(id)) {
String urlimage = jjobject.getString("screenshot");
String total = url + urlimage;
// mess.setText(total);
if (imageid.equals("105")){
images1[k] = total;
k++;
totals=images1;
}
else if (imageid.equals("106")){
images2[k] = total;
k++;
totals=images2;
}
else if (imageid.equals("107")){
images3[k] = total;
k++;
totals=images3;
}
else if (imageid.equals("108")){
images4[k] = total;
k++;
totals=images4;
}
else if (imageid.equals("109")){
images5[k] = total;
k++;
totals=images5;
}
else if (imageid.equals("110")){
images5[k] = total;
k++;
totals=images5;
}
else if (imageid.equals("111")){
images6[k] = total;
k++;
totals=images6;
}
else{
totals=images7;
}
}
}
mProduct.setYourimages(totals);
mArrayList.add(mProduct);
mProduct = null;
}
You can use two approaches:
String[] arr;
ArrayList<String> arrList= new ArrayList<>();
Don't create individual string array.You can use Arraylist to make a dynamic String array.
ArrayList<String> images =new ArrayList<String>();
to insert values.Just use add() method.
For example,You want to store iamgeUrls then :
images.add(image1);
images.add(image2);
And to retrieve data use get() method.Example :
images.get(position); //where position is the index of imageUrl you want to retrieve.
You can use:
String[] array= new String[0];
Or
ArrayList<String> array=new ArrayList<String>();

ArrayList cannot be cast to java.util.ArrayList, toArray returns nothing

I am trying to write a hierarchal block that puts elements into an ArrayList, all apart of a larger ArrayList. What the block does is take an existing input of text, and adds every line of text into elements of an ArrayList. Each Line is then created as an ArrayList of Strings, with each String being a word on that line (I used the String Split at spaces (" ") to perform this).
My problem is when trying to create this I needed to use the Arrays.asList (because a String Split returns a List)
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<String> text = LinetoList(area);
//"text" is a String ArrayList of every "line" in a piece of text
//LinetoList is a method that returns an ArrayList based on each new line
ArrayList<ArrayList> words = new ArrayList();
for (int i = 0; i < text.size(); i++) {
ArrayList sentence = (ArrayList) Arrays.asList(text.get(i).split(" "));
/*Sentence is currently a list, however, changing the type to an Array
* or Arraylist Changes nothing */
words.add(sentence);
}
for (int k = 0; k < words.size(); k++) {
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));
}
}
}
};
This was my original Method which return the error. I have since adjusted slightly, which no longer returns an error BUT, doesn't return anything.
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<String> text = LinetoList(area);
//"text" is a String ArrayList of every "line" in a piece of text
//LinetoList is a method that returns an ArrayList based on each new "line"
ArrayList<ArrayList> words = new ArrayList();
for (int i = 0; i < text.size(); i++) {
ArrayList <String> sentences = new ArrayList();
String sentence[] = text.get(i).split(" ");
sentence = sentences.toArray(sentence);
/*Sentence is currently a list, however, changing the type to an Array
* or Arraylist Changes nothing */
words.add(sentences);
}
if (words.size() == 0)
{System.out.println("Theres nothing here"); }
else {
for (int k = 0; k < words.size(); k++) {
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));}
}
}
}
};
Any feedback or ideas on how to approach a solution is greatly appreciated.
EDIT: Some people asked for the LinetoList function. A majority of the program uses ArrayLists of strings which is why it's so heavily used here.
private static ArrayList<String> LinetoList(JTextArea textArea) {
String s[] = textArea.getText().split("\\r?\\n");
ArrayList<String>arrList = new ArrayList<>(Arrays.asList(s)) ;
return arrList;
}
I don't actually follow:
String sentence[] = text.get(i).split(" "); // here you have array
sentence = sentences.toArray(sentence); // WTF?
And now about that WTF mark - you are filling sencence array with content of sentences. WHat is better, I don't see declaration of sentences but I guess it is just empty right? Thats why you see it empty all the time. As for me, lot of strange code and useless comments in it.
1) Arrays.asList does not return java.util.ArrayList, if you want it to be ArrayList, then you need to do ArrayList sentence = new ArrayList( Arrays.asList(text.get(i).split(" ")));
2) toArray method puts all elements from collection into array. in your case, collection is empty as you are creating almost before you call method
So after taking a look at the comments on HOW the toArray and asList work, I tried a different approach that was based more on my linetolist function
the result was
Action Syllables = new AbstractAction("Syllables") {
public void actionPerformed(ActionEvent e) {
ArrayList<ArrayList> words = new ArrayList();
ArrayList<ArrayList> splitLines = new ArrayList();
ArrayList<String> characters = new ArrayList();
//^^goes to (As hierarchey )
ArrayList<String> text = LinetoList(area);
//text is a String ArrayList of every line in a text
//LinetoList is a method that returns an ArrayList based on each new line
for (int i = 0; i < text.size(); i++) {
//for each line we have
String sentence[] = text.get(i).split(" ");
ArrayList<String> splitText = new ArrayList<>(Arrays.asList(sentence));
words.add(splitText);
}
for (int j = 0; j < words.size(); j++) {
String sentence [] = text.get(j).split(" ");
ArrayList<String> splitText = new ArrayList<>(Arrays.asList(sentence));
ArrayList<ArrayList> SplitWords = new ArrayList();
for (int i =0; i < sentence.length; i++) {
ArrayList<Character> SplitCharacters = new ArrayList<Character>();
for (int k = 0; k < splitText.get(i).length(); k ++) {
SplitCharacters.add(splitText.get(i).charAt(k));
}
SplitWords.add(SplitCharacters);
}
splitLines.add(SplitWords);
if (words.size() == 0)
{System.out.println("Theres nothing here"); }
else {
for (int k = 0; k < words.size(); k++) {
System.out.println("\n");
for (int i= 0; i < words.get(k).size(); i ++) {
System.out.println(words.get(k).get(i));
}
}
System.out.println("That was the original method \n");
for (int k = 0; k < splitLines.size(); k++) {
System.out.println(splitLines.get(k).toString() + "\n");
}
}
}
}
};
I included two different approaches to this problem, one that simplifies things as an ArrayList of words and one that gives an ArrayList of ArrayList of Characters (or a array list of words which hold letters)
Thanks for all the help. Hopefully anyone else can take something away from my blunders.

ArrayList, Getting values, from index() to index()

Hi everybody I am trying to get values from an ArrayList I created. I have some indexes, and I want to print the data ONLY between the indexes I want, so far I ave done this, but it does not seem to work. I think the get() is not valid for want I want... Any ideas?
public static void main(String[] args) throws Exception {
Scanner dataSc = new Scanner(new FileReader("StudData1.txt"));
ArrayList<String> ArrayData = new ArrayList<String>();
ArrayList<String> idData = new ArrayList<String>();
ArrayList<String> idIndex = new ArrayList<String>();
int b = 0;
int a = 0;
int i = 0;
while (dataSc.hasNextLine()) {
String data = dataSc.nextLine();
ArrayData.add(i, data);
if (data.contains("ID: ")) {
idData.add(a, data);
idData.set(a, (idData.get(a).replaceAll("[\\D]", "")));
a++;
b++;
}
i++;
idIndex.add(b, Integer.toString(i));
}
int idSt1 = Integer.parseInt(idData.get(0));
int idSt2 = Integer.parseInt(idData.get(1));
int idSt3 = Integer.parseInt(idData.get(2));
int idxID1 = Integer.parseInt(idIndex.get(0));
int idxID2 = Integer.parseInt(idIndex.get(1));
int idxId3 = Integer.parseInt(idIndex.get(2));
if (idSt1 < idSt2 && idSt2 < idSt3) {
System.out.println(ArrayData.get(idxID1-3 , idxID2-3 );}
}
}
}
Its easy done with a for-loop.
for(int i = startindex+1; i<endindex; i++) {
System.out.println(ArrayData.get(i));
}
This loop will print all objects in the arraylist that are between the given indices.
But there is no method called get() which returns a collection of items that are between to given indices, you can only use the subList(arg0, arg1) method to creat a subcollection and then iterate over this subcollection. Take a look at the Docs http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#get%28int%29
Example:
List<String> al = new ArrayList<>();
al.add("a");
al.add("b");
al.add("c");
al.add("d");
List<String> sublist = al.subList(0, 3); //inclusive index 0, exclusive index 3
for(String s : sublist)
System.out.println(s);
Output: a, b, c
Problem is in your code:
System.out.println(ArrayData.get(idxID1-3 , idxID2-3 );
The get method of class ArrayList accepts only one argument, here you are passing two.
You can use subList(int fromIndex, int toIndex) to get your desired result.
You can take range of values by index from ArrayList as follows.
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
for(int i=0;i<4;i++){
if(i<=2 && i>=1){
System.out.println(list.get(i));
}
}
i would do it like that
if (idSt1 < idSt2 && idSt2 < idSt3) {
for (int j = idxID1-3; j < idxID2-3; j++){
System.out.println(ArrayData.get(j));
}
}

List of List<String> to string ordered string array

I am having a resultList which is a string list were each element in this list is also a List<String>. Now I want to put my data into a csv sheet. For that I am using opencsv.
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < resultList.get(0).size(); m++) {
for (int i = 0; i < resultList.size(); i++) {
data.add(new String[] {resultList.get(i).get(m).toString()});
}
}
writer.writeAll(data);
//close Writer
writer.close();
My data should look like that:
However, my implementation gives me that:
In my implementation I am taking, knowing that every sublist has the same length, from each sublist the first element and add it to the array. Why am I getting this long row?
I appreciate your replies!
Because your loop is incorrect. You constructed a new String array in every inner loop, so every array has only on element.
Try the following code:
List<String[]> data = new ArrayList<String[]>();
for(List<String> strlist : resultList) {
String[] array = new String[strlist.size()];
int offset = 0;
for(String s : strlist) {
array[offset ++] = s;
}
data.add(array);
}
============== Edited bellow ==================
I've re-ordered the loop to match your output requirement. Also, a sample input is provided to test the algorithm.
List<List<String>> resultList = new ArrayList<List<String>>();
for (int i = 1; i <= 9; i++) {
List<String> innerList = new ArrayList<String>();
resultList.add(innerList);
for (int j = 1; j <= 9; j++) {
innerList.add(j + "");
}
}
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < resultList.get(0).size(); m++) {
String[] array = new String[resultList.size()];
for (int i = 0; i < resultList.size(); i++) {
array[i] = resultList.get(i).get(m).toString();
}
data.add(array);
}
for(String[] array : data) {
System.out.println(Arrays.toString(array));
}

removing an element from String array in android

Am doing a simple android application.In that I am deleting an element from array using the following code.
arr_fav = {"1","2","3"};
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
arr_fav[1] = null;
} }
By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.
its better to use arraylist
arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
// No operation here
}
else
{
numlist.add(arr_fav[i]);
}
}
arr_fav = numlist .toArray(new String[numlist .size()]);
You don't.
Arrays can not be resized.
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.
A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.
Arrays in Java are not dynamic, you can use an ArrayList instead.
You can copy the array elements that you want into a new array
j = 0;
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id != Integer.parseInt(arr_fav[i]))
{
arr_new[j++] = arr_fav[i];
} }
Use an ArrayList instead of an array. It supports features like deleting any element, dynamic size, and many more.
ArrayList<String> arr_fav_list = new ArrayList<String>();
arr_fav_list.addAll(arr_fav);
arr_fav_list.remove(1);
This will do the job ...
List x = new ArrayList(Arrays.asList(arr_fav));
x.remove(String.valueOf(current_id));
arr_fav = x.toArray();
try this:
ArrayList<String> rm = new ArrayList<String>();
rm .addAll(arr_fav);
rm .remove(1);
Try something like this
int[] intAry = new int[5];
// populate array with 0 to 4
for (int i=0; i < intAry.length; i++) {
intAry[i] = i;
}
List<Integer> aList = Arrays.asList(intAry); // change the array to a list of integers
aList.remove(3); // remove the item 3 (4th index)
aList.toArray(intAry); // convert list back to array
System.out.println("size of array=" + intAry.size()); // output array size should be 4
for (int i=0; i < intAry.length; i++) {
System.out.print(intAry[i] + " "); // should output "0 1 2 4 "
}
set
array_fav[1]=array_fav[2];
array_fav[2]=null;
You can do it using the following method..
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
OR you could use ArrayUtils.
array = ArrayUtils.removeElement(array, element)
For simple arrays like this you can't do this in this way
here is the full sample code for this
int current_id = 2;
String[] arr_fav = { "1", "2", "3" };
for (int i = 0; i < arr_fav.length; i++) {
if (current_id == Integer.parseInt(arr_fav[i])) {
String[] arr_fav_tem = new String[arr_fav.length - 1];
arr_fav[1] = null;
int counter = 0;
for (int j = 0; j < arr_fav.length; j++) {
if (arr_fav[j] != null) {
arr_fav_tem[counter] = arr_fav[j];
counter++;
}
}
arr_fav = arr_fav_tem;
}
}
for (int i = 0; i < arr_fav.length; i++) {
System.out.println(arr_fav[i]);
}
String[] arr_fav =
{ "1", "2", "3" };
List<String> myList = Arrays.asList(arr_fav);
String currentId = String.valueOf(current_id);
for (int i = 0; i < arr_fav.length; i++)
{
if (arr_fav[i].equals(currentId))
{
myList.remove(i);
}
}
private String[] removeItem(String[] names,
int position) {
ArrayList<String> al_temp=new ArrayList<String>();// temporary ArrayList
for(int i=0;i<names.length;i++)
{
al_temp.add(names[i]);
}
al_temp.remove(position);
names= new String[al_temp.size()];//array cleared with new size
for(int i=0;i<al_temp.size();i++)
{
names[i]=al_temp.get(i);
}
return names;
}
Copy this method:
private static String[] deleteElement(String stringToDelete, String[] array) {
String[] result = new String[array.length];
int index = 0;
ArrayList<String> rm = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
rm.add(array[i]);
}
for(int i = 0; i < array.length; i++) {
if(array[i].equals(poistettava)) {
index = i;
}
}
rm.remove(index);
result = rm.toArray(new String[rm.size()]);
return result;
}
To delete element:
String[] array = {"1", "2", "3"};
array = deleteElement("3", array);

Categories

Resources