I am new to Android and Java and can't figure out this seemingly basic for loop setup to create an array of objects from the data in two other arrays.
It works this way, but this doesn't feel very sophisticated.
// RefineMenuItem is a public class
public class RefineMenuItem {
private int imageIcon;
private String title;
}
// imageIcon and title are arrays with seven values in them
int[] imageItems = { ... }
String[] menuItems = { ... }
// Create the RefineMenu Objects
RefineMenuItem item1 = new RefineMenuItem(imageItems[0],menuItems[0]);
RefineMenuItem item2 = new RefineMenuItem(imageItems[1],menuItems[1]);
RefineMenuItem item3 = new RefineMenuItem(imageItems[2],menuItems[2]);
RefineMenuItem item4 = new RefineMenuItem(imageItems[3],menuItems[3]);
RefineMenuItem item5 = new RefineMenuItem(imageItems[4],menuItems[4]);
RefineMenuItem item6 = new RefineMenuItem(imageItems[5],menuItems[5]);
RefineMenuItem item7 = new RefineMenuItem(imageItems[6],menuItems[6]);
// Add the RefineMenu Objects to an ArrayList
ArrayList<RefineMenuItem> refineMenuList = new ArrayList<>();
refineMenuList.add(item1);
refineMenuList.add(item2);
refineMenuList.add(item3);
refineMenuList.add(item4);
refineMenuList.add(item5);
refineMenuList.add(item6);
refineMenuList.add(item7);
I believe I need to create the array of objects first and then add to it based on this question.
RefineMenuItem[] arr = new RefineMenuItem[7];
Then I believe I should use a for loop to add to the array, but this is where I'm getting stuck and can't figure it out after researching. Help to point me in the right direction is appreciated!
A basic for loop could solve all your problems I believe.
Just make sure you make your implementations/declarations before.
for(int i = 0; i<=6; i++) {
RefineMenuItem item = new RefineMenuItem(imageItems[i],menuItems[i]);
refineMenuList.add(item);
}
I'm gonna be brutally honest, haven't worked with java in a while so there might be some syntax errors but the logical solution should be supplemental.
It is impossible to create an ArraysList directly from two arrays. You first, need to create an array of the RefineMenuItem objects and add them. However, instead of creating a new array just to add all at once, create them as soon as you instantiate them... Like:
int size;
if(imageItems != null && menuItems != null && menuItems.length == imageItems.length) {
size = menuItems.length;
} else {
size = 0;
}
ArrayList<RefineMenuItem> refineMenuList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
refineMenuList.add(new RefineMenuItem(imageItems[i],menuItems[i]));
}
A precondition is that imageItems and menuItems have the same number of elements in them. So I'd start by asserting that.
Then you can create a new array of the same size, and use a for loop to iterate:
int[] imageItems = { ... }
String[] menuItems = { ... }
if (imageItems.length != menuItems.length) {
throw new IllegalStateException("array lengths don't match");
}
RefineMenuItem[] result = new RefineMenuItem[imageItems.length];
for (int i = 0; i < imageItems.length; ++i) {
result[i] = new RefineMenuItem(imageItems[i], menuItems[i]);
}
When this code completes, the result array will be fully populated.
// RefineMenuItem is a public class
public class RefineMenuItem {
private int imageIcon;
private String title;
}
// imageIcon and title are arrays with seven values in them
int[] imageItems = { ... }
String[] menuItems = { ... }
// create array list
ArrayList<RefineMenuItem> refineMenuList = new ArrayList<>();
// add items to the array list in a for loop
for (int i = 0; i < imageItems.length; i++) {
refineMenuList.add(new RefineMenuItem(imageItems[i], menuItems[i]));
}
This is assuming the imageItems and menuItems are always the same length
The premise of this is you can create the ArrayList and then use a for loop to iterate over your imageItems and menuItems, create a new RefineMenuItem from them, and add it to the refineMenuList
you should be adding it to a class array this way:
import java.util.ArrayList.add
RefineMenuItem[] items = new RefineMenuItem();
for(int i=0 ; i<7 ; i++ ){
RefineMenuItem thing = new RefineMenuItem(RefineMenuItem(imageItems[i],menuItems[i])
items[i].add(i,thing))
}
Related
I am trying to create an ArrayList from a given array. This is the array I have:
public class Warehouse
{
private final static int MAX = 60;
private Item [] stock;
private int numItems;
public Warehouse()
{
stock = new Item[MAX];
numItems = loadData();
}
Now where should I change the processing from an array to an arraylist? Is this supposed to be done in the constructor or somewhere else? Thanks.
Why not use this?
List<Item> stockList = Arrays.asList(stock);
Just keep a separate class for the array and within the class that you want to get that specific array you can create an ArrayList Object.
public class ArrayaData {
public int Id;}
And the within the next class,
public class ClassYouWant {
ArrayList<ArrayaData> arrayList ;
}
and when ever you want to add a value to that array just create a new instance and then save it.
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value you want.."
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value 2 you want.."
Or you can simply set it in a Loop as well,
int arraySize = 5; //Size of the array you want
for (int i = 0; i < arraySize; i++) {
arrayList = new ArrayList<ArrayData>();
arrayList.Id = "Value you want";
}
And to get the vlaues you can use a Loop also,
int arraySize = arrayList.size(); //Size of the created arrayList
int value;
for (int i = 0; i < arraySize; i++) {
value = arrayList.get(i);
Toast.makeText(this, "Value " + i + ":" + value, Toast.LENGTH_SHORT).show();
}
Hope this helps..
how Can I fill an array bidimensional without a specific number of columns?
private Animals[] animals;
private Animals[][] matrizAnimal;
private final int MAX_ANIMALS = 20;
private int numAnimals;
CatalogueAnimals()
{
animals = new Animals[MAX_ANIMALS];
numAnimals = 4;
matrizAnimal = new Animals [2][];
animals[0] = new Dog("Pipi", 10);
animals[1] = new Cat("mimi", 4);
animals[2] = new Cat("jerry", 5);
animals[3] = new Cat("josh", 9);
}
public void fillArrayBi()
{
int i=0;
do{
for (int col=0; col<matrizAnimal.length; col++)
{
if (animals[i] instanceof Dog)
{
matrizAnimal[0][col] = animals[i];
}
else if (animals[i] instanceof Cat)
{
matrizAnimal[1][col] = animals[i];
}
i++;
}
}while(i<numAnimals);
}
I'm trying to fill the array. The first row contains 'Dogs' and the second row contains 'Cats'.
Thanks
for (int col=0; col<matrizAnimal.length; col++)
{
if (animals[i] instanceof Dog)
{
matrizAnimal[0][col] = animals[i];
}
...
}
This won't work due to a number of reasons:
col is bounded by the first dimension of matrizAnimal which is 2, thus it is somewhat risky to apply the value to the second dimension
you created matrizAnimal but I can't see any code where you initialize the elements, hence matrizAnimal[0][col] will result in a NullPointerException because the element at index 0 doesn't exist yet
If I understand your question correctly you want to create the 2nd dimension of matrizAnimal with a length calculated at runtime.
For that you'd have two options:
If you know the length when creating the second dimension, you can pass that directly to the construction call:
int lengthOfRow = 4;
matrizAnimal[0] = new Animals[lengthOfRow];
If the length depends on the elements in that second dimension array you could use a list, fill that and finally convert it to an array:
List<Animals> list = ...;
//fill list
matrizAnimal[0] = list.toArray(new Animals[list.size()]);
Edit:
To clarify on multi-dimensional arrays: arrays can only be one-dimensional but can contain other arrays. Hence a "multi-dimensional" array is actually an array containing arrays etc. In contrast to other languages like C++ the entire array is not laid out in contiguous memory.
In Java arrays need size to be declared, so you must know the number of columns when creating the array. I would make this approach in a different way using Collections
You can use 2 ArrayList, or if you want only one object, a Map:
Create and initialize Map
Map<String, List<Animals>> animalsMap = new HashMap<String, List<Animals>>();
Then,
if (animals[i] instanceof Dog)
{
if (animalsMap.get("Dog") != null)
{
animalsMap.put("Dog", animalsMap.get("Dog").add(animals[i]));
} else {
List<Animal> a = new ArrayList<Animal>();
a.add(animals[i]);
animalsMap.put("Dog", a);
}
}
else if (animals[i] instanceof Cat)
{
if (animalsMap.get("Dog") != null)
{
animalsMap.put("Cat", animalsMap.get("Dog").add(animals[i]));
} else {
List<Animal> a = new ArrayList<Animal>();
a.add(animals[i]);
animalsMap.put("Cat", a);
}
I have defined a class Note that represents a way to play a certain note (two integers for the string and fret on a string instrument), and a class Chord which has an ArrayList of all the notes in that chord.
For every note that is played there may be multiple ways of playing that note so I have an ArrayList of Notes representing each possible way. In a chord there can be any number of notes so I have an ArrayList of ArrayLists of Notes. From this I want to create an ArrayList of chords with each possible way of playing the chord.
I have defined a constructor Chord(ArrayList<Note> notes)
eg:
Note A has 3 ways of being played and note B 2 ways of being played, from this I would want chords with:
[A1,B1], [A1,B2], [A2 B1], [A2 B2], [A3,B1], [A3,B2].
I have created a method that works under the assumption that there are always 3 notes played but can't think how to expand it to work for an unknown number
public static ArrayList<Chord> allPlayable(ArrayList<ArrayList<Note>> candidates)
{
ArrayList<Chord> allPlayable = new ArrayList<>();
for (int i = 0; i < candidates.get(0).size(); i++)
{
Note n0 = candidates.get(0).get(i);
for (int j = 0; j < candidates.get(1).size(); j++)
{
Note n1 = candidates.get(1).get(j);
for (int k = 0; k < candidates.get(2).size(); k++)
{
Note n2 = candidates.get(1).get(k);
ArrayList<Note> chordNotes = new ArrayList<>();
chordNotes.add(n0);
chordNotes.add(n1);
chordNotes.add(n2);
allPlayable.add(new Chord(chordNotes));
}
}
}
return allPlayable;
}
IT was suggested to me to use recursion - every for loop would be another recursive call and I came up with this answer
public static ArrayList<Chord> allPlayable(ArrayList<ArrayList<Note>> candidates)
{
//this will be the inner ArrayList we are on
ArrayList<Note> current = new ArrayList();
//the list of chords to return
ArrayList<Chord> allPlayable = new ArrayList();
allPlayableRecurse(candidates, 0, current, allPlayable);
return allPlayable;
}
public static void allPlayableRecurse(ArrayList<ArrayList<Note>> candidates, int index, ArrayList<Note> chordNotes, ArrayList<Chord> allPlayable)
{
ArrayList<Note> current = candidates.get(index);
//for each note in the current array list of notes
for (int i = 0; i < current.size(); i++)
{
chordNotes.add(current.get(i));
//there are more notes to add
if (index < candidates.size()-1)
{
//go to the next inner ArrayList
allPlayableRecurse(candidates, index+1, chordNotes, allPlayable);
}
else//we have reached the last note
{
//add the chord to the list
allPlayable.add(new Chord((ArrayList<Note>)chordNotes.clone()));
}
//we will now replace this note
chordNotes.remove(chordNotes.size()-1);
}
}
You could use recursion, for example:
List<List<Note>> combine(List<List<Note>> representations) {
List<Note> options = representations.get(0);
List<List<Note>> tails;
if (representations.size()==1) {
tails = new ArrayList<>();
tails.add(Collections.emptyList());
} else {
tails = combine(representations.subList(1, representations.size()));
}
List<List<Note>> combinations = new ArrayList<>(options.size());
for (Note note : options) {
for (List<Note> tail : tails) {
List<Note> chord = new ArrayList<>();
chord.add(note);
chord.addAll(tail);
combinations.add(chord);
}
}
return combinations;
}
public List<Chord> allPlayable(List<List<Note>> candidates) {
List<List<Note>> combinations = combine(candidates);
List<Chord> chords = new ArrayList<>(combinations.size());
for (List<Note> notes : combinations) chords.add(new Chord(notes));
return chords;
}
It is the old java7 style. It can be done easier with new Java8 functional operations but not sure if it is already your thing if you just started.
I know it's simple question, but in
ArrayList<ArrayList<String>> collection;
ArrayList<String> listOfSomething;
collection= new ArrayList<ArrayList<String>>();
listOfSomething = new ArrayList<String>();
listOfSomething.Add("first");
listOfSomething.Add("second");
collection.Add(listOfSomething);
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
I want to take String from ArrayList of ArrayList, and I don't know how to do that. For example I go
ArrayList<String> myList = collection.get(0);
String s = myList.get(0);
and it works! but:
Big update:
private List<S> valuesS;
private List<Z> valuesZ;
ArrayList<ArrayList<String>> listOfS;
ArrayList<String> listOfZ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Zdatasource = new ZDataSource(this);
Zdatasource.open();
valuesZ = Zdatasource.getAllZ();
Sdatasource = new SDataSource(this);
Sdatasource.open();
valuesS = Sdatasource.getAllS();
List<Map<String, String>> groupData
= new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData
= new ArrayList<List<Map<String, String>>>();
listOfS = new ArrayList<ArrayList<String>>();
listOfZ = new ArrayList<String>();
for (S i : valuesS) { // S is class
for (Z j : valuesZ) { // Z is class
if(j.getNumerS().equals(i.getNumerS())) {
listOfZ.add(j.getNumerZ());
}
else
{
//listOfZ.add("nothing");
}
}
listOfS.add(listOfZ);
if(!listOf.isEmpty()) listOfZ.clear();
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
try
{
ArrayList<String> myList = listOfS.get(groupPosition);
String s = myList.get(childPosition);
PrintToast("group "+Integer.toString(groupPosition)+", child "+Integer.toString(childPosition) + " , "+ s);
}
catch(Exception e)
{
Log.e("FS", e.toString());
}
return true;
}
return me java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
when I click on item which really should exist. I didn't show code which generate ListView, but I can tell you that my listOfS contains 3 items:
first is Null listOfZ, second listOfZ got 2 elements, third listOfZ got 1 element.
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething); save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
A cleaner way of iterating the lists is:
// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
for (String string : innerList) {
// do stuff with string
}
}
I have String array like this
We have to pass data through response.body.getdata and this data pass in constructor like this,
List taginnerData;
"data": [
"banana",
"apple",
"grapes",
"Pears",
"Mango",
"Cherry",
"Guava",
"TorontoVsMilwaukee_12Jan19"
]
String[] myArray = new String[taginnerData.size()];
for (int i = 0; i < taginnerData.size(); i++) {
myArray[i] = String.valueOf(taginnerData.get(i));
holder.tv_channel_name.setText("" +taginnerData.get(i));
//we get any value from here to set in adapter
}
This question already has answers here:
How to most elegantly iterate through parallel collections?
(8 answers)
Closed 6 years ago.
I Have Two Array Lists, Declared as:
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
Both of the these fields contain exactly, the Same No of Values, which are infact corresponding in Nature.
I know I can iterate over one of the loops like this:
for(JRadioButton button: category)
{
if(button.isSelected())
{
buttonName = button.getName();
System.out.println(buttonName);
}
}
But, I would like to iterate over both the LISTS simultaneously. I know they have the exact same size. How do I Do that?
You can use Collection#iterator:
Iterator<JRadioButton> it1 = category.iterator();
Iterator<Integer> it2 = cats_ids.iterator();
while (it1.hasNext() && it2.hasNext()) {
...
}
java8 style:
private static <T1, T2> void iterateSimultaneously(Iterable<T1> c1, Iterable<T2> c2, BiConsumer<T1, T2> consumer) {
Iterator<T1> i1 = c1.iterator();
Iterator<T2> i2 = c2.iterator();
while (i1.hasNext() && i2.hasNext()) {
consumer.accept(i1.next(), i2.next());
}
}
//
iterateSimultaneously(category, cay_id, (JRadioButton b, Integer i) -> {
// do stuff...
});
If you do this often you may consider using a helper function to zip two lists into one pair list:
public static <A, B> List<Pair<A, B>> zip(List<A> listA, List<B> listB) {
if (listA.size() != listB.size()) {
throw new IllegalArgumentException("Lists must have same size");
}
List<Pair<A, B>> pairList = new LinkedList<>();
for (int index = 0; index < listA.size(); index++) {
pairList.add(Pair.of(listA.get(index), listB.get(index)));
}
return pairList;
}
You will also need a Pair implementation. Apache commons lang package has a proper one.
And with these you can now elegantly iterate on the pairlist:
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
for (Pair<JRadioButton, Integer> item : zip(category , cat_ids)) {
// do something with JRadioButton
item.getLeft()...
// do something with Integer
item.getRight()...
}
Try this
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
for (int i = 0; i < category.size(); i++) {
JRadioButton cat = category.get(i);
Integer id= cat_ids.get(i);
..
}
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
Iterator<JRadioButton> itrJRB = category.iterator();
Iterator<Integer> itrInteger = cat_ids.iterator();
while(itrJRB.hasNext() && itrInteger.hasNext()) {
// put your logic here
}
Although you are expecting both sizes to be same, just to be on safer side get the sizes for both of them and make sure they are equal.
Let that size value be count. Then use generic for loop, iterate till count and acess the values as array indexes. If 'i' is the index, then acess as below in the for loop.
category[i] and cat_ids[i]
category[i].isSelected() and so on