This question already has answers here:
Initializing an array in Java using the 'advanced' for each loop [duplicate]
(5 answers)
Closed 5 years ago.
I have 2 classes. The first describes an item, and the seconds is built around an array of items of the first class.
I had learned that just creating an array of objects doesn't initialize them. So I put a for-loop in the constructor of the 2nd class to initialize all items.
Yet when entering the clear() function, all elements of the list array are still null. Why is that?
class HneAnalogItem {
String description;
String unit;
float value;
HneAnalogItem(){}
}
class HneAnalogInfo
{
static final private int MAXANALOGINFOITEMS = 100;
private HneAnalogItem[] list;
HneAnalogInfo() {
list = new HneAnalogItem[MAXANALOGINFOITEMS];
for(HneAnalogItem item : list) {
item = new HneAnalogItem();
}
clear();
}
void clear() {
for(HneAnalogItem item : list) {
item.description = "";
item.unit = "";
item.value = 0;
}
}
}
for (HneAnalogItem item : list) {
item = new HneAnalogItem();
}
This enhanced for loop doesn't initialize the array elements. It is equivalent to:
for (int i = 0; i < list.length; list++) {
HneAnalogItem item = list[i];
item = new HneAnalogItem();
}
To initialize the array elements you need:
for (int i = 0; i < list.length; list++) {
list[i] = new HneAnalogItem();
}
Related
so i've created this function as a game :
public static ArrayList<Character> spreadCardsOnTable(char[] cards) {
ArrayList<Character> newCards = new ArrayList<Character>();
Queue<Character> q = new LinkedList<>();
while (cards.length != 0) {
int k = 0;
for (int i = 0; i <= cards.length - 1; i++) {
if (i % 2 == 0) {
newCards.add(cards[i]);
} else {
q.add(cards[i]);
k++;
}
}
cards = new char[k];
for (int j = 0; j <= k - 1; j++) {
cards[j] = q.poll();
}
}
return newCards;
}
the game goes as for example if we have an array made of ['W','B','B','B','W','W']
after i run the function i made i get an output of ['W','B','W','B','W','B'] as it is now organized
now on the second function i need to do is: given an int "n" i should find the original array ['W','B','B','B','W','W'] before sending it to the first function and organizing it as the example goes ['W','B','W','B','W','B'] like reversing it, i've tried several ways but all of them failed
the title of the function is :
public static ArrayList createOriginalLayout(int n)
No. Once you've dereferenced the original list then it's original indexing is gone unless you preserve the original sorting order within the items in the list itself, but that would be very strange.
What I'd do is create a class to hold the original data and offer up a presentation function for the sorted data. Something like:
public class CardLayout {
private List<Character> originalList;
public CardLayout(List<Character> list) {
originalList = list;
}
public List<Character> getOriginalList() {
return originalList;
}
public List<Character> getSortedList() {
//edit: Note that your original method is destructive to
//the original data, so you would need to copy the data
//into another structure before proceeding.
//either do your spreadCardsOnTable() method here or
//precalculate it, store it, and return it here.
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Is it possible to emulate a linked list in java by nesting a class within a class? I have tried to implement, but the summation function doesn't move passed the first class. This generates a 1 no matter what integer it is given:
public class Example {
static class Item{
boolean b;
double d;
Item nextItem;
Item (boolean b, double d, Item nextItem) {
this.b = b;
this.d = d;
this.nextItem = nextItem;
}
}
static double f(Item item) {
if(item != null)
return (item.b ? item.d : 0.0) + f(item.nextItem);
else
return 0.0;
}
static public void main(String args[]) {
int n = Integer.parseInt(args[0]);
Item firstItem = null;
firstItem = new Item((1%2!= 0), Math.sqrt(1), null);
if(n > 1){
Item nextItem = firstItem.nextItem;
for (int i = 2; i <= n; i++) {
nextItem = new Item((i%2!=0), Math.sqrt(i), null);
nextItem = nextItem.nextItem;
}
}
double s = f(firstItem);
System.out.println("sum = " + s);
}
}
Of course you can implement a LinkedList using nested classes. There are many ways to do it. Here you have an example: LinkedList example
But the problem you have is the variable firstItem never change. You assing the value here:firstItem = new Item((1%2!= 0), Math.sqrt(1), null);
and then you loop another variable Item nextItem = firstItem.nextItem; that is always null.
Remove the argument nextItem of constructor if you alaways set it to null.
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..
When I acces to list of list with this function,It make ConcurrentModificationException in second for loop but i don't understand why this Exception is triggered .
public static List<List<Dico>> weight_term(List<List<Dico>> sublists ,List<String> sinificativ )
{
List<List<Dico>> matrix_node_term = new ArrayList<>();
List<Dico> list_node = new ArrayList<>();// a new list for node
for (List<Dico> sublist : sublists) // to get each sublist List<Dico>
{
for (Dico dico : sublist) // get each Dico in the sublist -->ConcurrentModificationException
{
String term =dico.getTerm();
int id = dico.getDocId();
if(sinificativ.contains(term)) // if this term exist in sinificativ erm list
{
list_node.add(dico); // it add to list_node
}
else
{
list_node.add(new Dico(id,term,0.0)); // it add to list_node with null weigth
}
}
matrix_node_term.add(list_node); // add each list to list of list
}
return matrix_node_term;
}
The dico class is used to store term,id of document and the weight of this term in that document :
public class Dico implements Comparable
{
private final String m_term;
private double m_weight;
private final int m_Id_doc;
public Dico(int Id_Doc,String Term,double tf_ief )
{
this.m_Id_doc = Id_Doc;
this.m_term = Term;
this.m_weight = tf_ief;
}
}
This Exception is triggered without any modification in the sutucte of list or its elements .
Probleme comes from a function used to split List in multiple List:
List<List<Dico>> sublists = new ArrayList<>(change);
for (int i = 0; i < change; i++)
{
sublists.add(list.subList(changes[i],changes[i + 1]));
}
A solution comes from pbabcdefp
List<List<Dico>> sublists = new ArrayList<>(change);
for (int i = 0; i < change; i++)
{
sublists.add(newArrayList<Dico>(list.subList(changes[i], changes[i + 1])));
}
thank you for your help
If I have the following class:
public class Hello {
private String name;
public Hello(String n) {
this.name = n;
}
public int getSize(int x) {
return x + (this.name.length());
}
}
Now if I wish to create an array of 5 Hello objects, I could say
Hello[] t = new Hello[5];
My question is:
i) How do I call the constructor on each of elements of the array t
ii) After I have called the constructor, how can I call the method and pass the argument x to each element of the array?
i) How do I call the constructor on each of elements of the array t
Traverse each element of the array and initialize the elements using the proper constructor and arguments:
for (int i = 0; i < t.length; i++) {
t[i] = new Hello("some string");
}
ii) After I have called the constructor, how can I call the method and pass the argument x to each element of the array?
Again, traverse the array and call the desired method on the array element.
int x = ...; //define some value
for (int i = 0; i < t.length; i++) {
System.out.println(t[i].getSize(x));
}
If you want each instance of Hello to contain a different string I'd initialize an array of strings first and then iterate over those to create the array of Hello instances. You also don't need to traverse the array twice, as you can initialize and then call the method. You could also abstract this into a static method in the Hello class as a static constructor.
public class Hello {
...
public static final Hello[] fromStrings(final String[] words, final int x) {
final Hello[] hellos = new Hello[words.length];
for (int i = 0; i < words.length; i++) {
hellos[i] = new Hello(words[i]);
System.out.println(hellos[i].getSize(x));
}
return hellos;
}
}