Checking size of stack (ArrayList) in Java? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to implement a stack with an Array List.
BlueJ tells me that "size" has private access in java.util.ArrayList even though the Array List is public, when I'm compiling.
int stackLength = stackStorage.size;
System.out.println(+stackLength);
And if I change the line to..
int stackLength = stackStorage.size();
the program compiles and I get a nullPointerExcetion when I run the function.
I don't understand why this is happening because a value cannot be manually assigned because the value needs to come from the stack size.
Any help appreciated, cheers.

You can't directly call for the variable (because it's a private field). You should use stackStorage.size() instead. Also make sure stackStorage is actually instantiated.
You most probably have:
ArrayList<Object> stackStorage;
However you must instantiate it somewhere like so:
stackStorage = new ArrayList<Object>();
This may also be done on the same line:
ArrayList<Object> stackStorage = new ArrayList<Object>();
Once you have created this ArrayList do note that it still doesn't have any elements in it. In order to actually add an Integer to the array simply do:
stackStorage.add(number);
And after you do that, if you call stackStorage.size() it should return 1, meaning there's one element in the ArrayList. If you wish to add more, simply use the add() method. Also make sure you add the same object as you instantiated it with. You can't store String in ArrayList<Integer> for example.
Full-code example:
ArrayList<Integer> stackStorage = new ArrayList<Integer>();
stackStorage.add(10); //Now has value `10` in `index[0]`
System.out.println("index[0]: " + stackStorage.get(0)); //Prints 10
System.out.println("stackStorage.size() = " + stackStorage.size()) //Prints 1
In your case replace Object with Integer if you wish to store integers. NullPointerException means your object is still null when you tried to call size(). This should solve your issue. If you're not sure what null is or don't quite understand what NPE(NullPointException) is I suggest reading about it and if you have further difficulties, posting it here.

That's because size is a private field and hence you don't have access to it, where size() is a public method that you can use. Therefore call size() to get the size of the ArrayList. The NullPointerException has nothing to do with size it is simple because your object is not initialized, make sure you initialize your objects before using them.
List<Something> list = new ArrayList<Something>();

size is a private variable
size() is a public method
For getting the size of the arrayList , you need to use size() and before calling size() dont forgot to intialize the array List like below .
List list = new ArrayList();

Related

referring to this only (not attributes), possible? [duplicate]

This question already has answers here:
Why is assignment to 'this' not allowed in java?
(7 answers)
Closed 1 year ago.
Context (not strictly necessary to understand the question):
I have to implement a collection of elements. The class is called DocumentCollection. It is essentially an array of lists (a rudimentary form of a hash array), better formulated: an array of references to the first element of each respective list.
I already implemented a basic constructor, which takes an int as size of the array, and puts null initialized lists in each bucket.
One method to implement is removeAll. My first idea was to generate a new collection of the same size as the original one, and assign this to this newly created collection.
Below the code of the method.
public boolean removeAll(){
if(isEmpty()){
return false;
}
int size = buckets.length;
this = new DocumentCollection(size);
return true;
}
where buckets is the array.
As this is part of an assignment, I don't want to include the code of the whole class. This is enough for my question.
Intellij gives me the following error message (w.r.t. the line with this): variable expected.
Unfortunately this message is not eloquent enough for me to understand it.
Aside Note: yes, I could iterate over the array and assign null lists to them. That's not the point I am trying to make here
Question:
Am I doing something fundamentally wrong? In other words, is trying to give a new reference to the current object (i.e. this) illegal? Or can it be done, and I am simply using some wrong syntax?
You can't assign a new value to this since it is just a keyword to represent the current object along the class code, it is not a variable.
Beside's that, think of the semantics: you are inside the object asking it to become another object, that would be very tricky!
The closest you can get to that is to wrap some object as a field of your class, then you can assign a new instance to this field. Like this:
class MyObjectWrapper{
private MyObject myObject = new MyObject();
...
public void removeAll() {
this.myObject = new MyObject();
}
}
Check this related question: Why is assignment to 'this' not allowed in java?

An Array of ArrayLists (Null Pointer Exception)

i'm currently trying to add items to an generic "array" of arraylists but for some reason i keep getting a null pointer exception. The Structure is initialised and both my array index reference and the reference to the object i'm passing in are both visible within the body of code right before the exception occurs. I'm almost sure its down to the way i either declared the data structure or my way im trying to add it in. Any advice would be appreciated. Thanks in advance
ArrayList<Site>[] group = (ArrayList<Site>[])new ArrayList[entranceSites.size()];
group[i].add(sIndex(path));
sIndex is a function I'm using to convert integers to graph sites and the object is not null when I'm passing it in so i'm sure its not the problem. I is initialised and also visible to the program.
new ArrayList[entranceSites.size()];
does not actually initialize the array elements with any constructor. The array will be filled with enteranceSites.size() null elements.
You will need to iterate through the array and actually construct ArrayList objects.
Here's how you can set each element of the array to a new ArrayList using Java 8:
Arrays.setAll(group, n -> new ArrayList<Site>());
(The second argument is a function of n, the array index, but n isn't actually used. You still need to include it.)
You have allocated an array of ArrayLists, but you have not allocated any actual ArrayLists inside that array. The array initially contains all null references. So your invocation to add is on a null reference and thus causes the exception. If you say:
group[i] = new ArrayList<Site>();
Before you call add it will work.
Note that it is generally a bad idea to mix primitive arrays and Java collections, and if you are new to Java, then you should probably stick to collections since they are going to be easier to work with.
You should also be aware that the cast you are making (ArrayList<Site>[]) is unchecked and will almost certainly generate a warning assuming you have warnings enabled, which you should be enabling warnings as a beginner. This is another reason why it is not a good idea to mix generics with primitive arrays.
By the looks of your code fragment, my guess is that you failed to initialize the ArrayList<Site> element being added to the array; thus, failing when calling the List.add() method. The array itself is properly initialized, but you are trying to add a Site to an ArrayList that has not been initialized properly.
For this to work, you must create your ArrayList<Site> object. Once your lists are properly instantiated, you can add them to the array. You can add Site objects when creating the list or after you add them to the array. It does not matter when because the space in memory will be already allocated. Suppose a company has sites in many states, for argument sake, New York. All of the sites in that geographical location will be added to the NY list of sites:
ArrayList<Site> nySites = new ArrayList<Site>();
Site site1 = new Site();
group[0] = nySites;
group[0].add(site1); // Now you can call the add() method

Showing list of what's in ArrayList [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a problem getting my JComboBox's drop down list to show a list of hotels by hotel name.
My ArrayList contains hotelNo, hotelName, city.
In my GUI, ive written this
Object[] hotelArr = { databaseconn.arrayListHere() };
#SuppressWarnings({ "rawtypes", "unchecked" })
// this just hide some unimportant warnings
JComboBox hotelList = new JComboBox(hotelArr);
hotelList.addActionListener(this);
frame.add(hotelList, BorderLayout.NORTH);
I can click the drop down list but it only shows "[]". Brackets I think they're called.
I want it to show the list of hotelName which is also stored in the ArrayList hotelInfo I've put in a method called arrayListHere.
So how do I do it? Spent many hours on this issue. Couldn't find an answer or help anywhere. I also checked the docs but didn't get anything I could use.
The way your Object[] hotelArr is defined was incorrect. Also, it's not possible to simply cast a list to an array. Instead, you must convert the list to a data structure, the JComboBox can handle. There are several posibilities:
1. (best in my opinion, because:
guarantees type safety, if you are handling classes other than Object
return type of arrayListHere() can be the interface Collection, which makes it more common, than a returned List
Collection<E> list = databaseconn.arrayListHere();
Vector<E> vector = new Vector(list);
JComboBox box = new JComboBox(vector);
2. if you stay with List as return type of arrayListHere()
Object[] array = databaseconn.arrayListHere().toArray();
JComboBox box = new JComboBox(array);
your problem is that you get a blank [] and treat is as an Array (well - hard to explain in words, i 'll use code to do so )..
//you *certainly* get an array here
Object[] list = databaseconn.arrayListHere();
//and as a result you get this code
Object[] hotelArr = new Object[]{ list } ;
when you get the message [] then certainlty that arry is empty, wich leads me to the assumption that databaseconn.arrayListHere() is an empty array
a workaround for you would be
Object[] hotelArr = (Object[]) databaseconn.arrayListHere();
but pleas check if that array before brining it to front!!
You said that your ArrayList have 3 type pf data i.e. hotelNo, hotelName, city.
& now you load it in Object[] hotelArr and then you are adding it to JComboBox.
So how application will understand that which among hotelNo, hotelName, city to take.
so make one another String[] that ll have hotelName only.
then try to load it in JComboBox, then it ll work. You can't directly add object to JCombobox when you are multiset data in Object Array.
If you are passing single set of data like hotemName then it ll work. see this :
List<String > ar = new ArrayList<>();
ar.add("hotel");
ar.add("hotel2");
ar.add("hotel3");
Object[] al = ar.toArray();
JComboBox j = new JComboBox(al);
System.out.println(j.getItemCount());
see this running example.

Is it possible to rename an ArrayList? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was just wondering if there is a way to rename the variable assigned to an ArrayList... Or if I just need to create another one, just making it exactly the same.
Just create a new reference with the name you want and assign it from the old reference:
ArrayList original = ...;
ArrayList newList = original;
I should point out that since ArrayList is a reference type, original and newList are both pointing to the same data in memory. If you add an item to original or to newList, it is going to affect both. It is not creating a second copy of the ArrayList. It is a little difficult to understand what you are asking for, though.
If you are talking about refactoring your code to rename the variable across the entire application, then it sort of depends on what IDE you are using, but any good IDE will have this capability.
First, I would just like to point out that 'renaming' a variable is not really a concept that bares any resemblance to the way that changing a 'reference' or 'identifier' works. You can't change a variables identifier (kind of like a variable's name), but you can pass the variable's value to another variable with a different identifier.
When a variable refers to an Object or child of the Object class (such as ArrayList), your reference type variable holds data indicating the position of that object in memory. So passing that reference's data to another reference just means there are now two Object references that 'refer' to the same object in memory.
Technically speaking, if you wanted to give that object a name that you could use to identify it later with, this is possible by creating a custom class that extends ArrayList (or whatever object). For example;
public class NamedArrayList extends ArrayList{
private String listName = "default_name";
public String getListName(){
return listName;
}
public void setListName(String listName){
this.listName = listName;
}
}
Alternatively, you could create a Wrapper class which holds an ArrayList as well as a name for identifying it. Apologies if the last part is a little off subject, but I hope it helps.
You can try this
List<Double> original =new ArrayList<Double>();
List<Double> copy = new ArrayList<Double>(original);
You can't rename any variable while the programm is running.
But you could rename it while developing. Then compile and run.
If you mean by renaming using a different reference than you can simply do
ArrayList newListRef = oldListInstance;
//use newListRef thereafter
If you mean to change some of the elements retaining the order then -
ArrayList is dynamic in size. You can add and remove elements to and from specific index and ordering in retained. So no need to create separate List. If you want to change a specific element simply remove it and add new element at that index.
APIs
public E remove(int index)
public void add(int index, E element)

Adding all wrong answers into an array with Java - how?

I want to take all the questions that were answered incorrectly (it's a simple program asking math questions) and if they got the question wrong, add the question number to the array for further use.
But, I don't know how long this array will be, it could theoretically be of a different length each time the program is ran. So how would I set up the array?
You should use an ArrayList instead.
You could do something like:
ArrayList<String> wrongAnswers = new ArrayList<String>();
// Call this function with the user's answer as a parameter, when the answer
// has been determined to be incorrect.
public void wrongAnswer(String answer) {
wrongAnswers.add(answer);
}
public void printWrongAnswers() {
System.out.println("Wrong answers:");
for (String answer : wrongAnswers) {
System.out.println(answer);
}
}
Start with an ArrayList and then you can call toArray() to get an actual array.
You can also initialize an array whose size is the number of questions you have. Then keep a running count of missed questions, and simply trim the array at the end.
Look into using an ArrayList. This is an implementation of the List interface that is backed by an array.
Using the default constructor, it will start with a backing array of size 10 (but don't worry too much about this detail):
List<Question> questionList = new ArrayList<Question>();
You can then add elements:
questionList.add(question);
It will then resize this array as needed as you continue to add elements.
Since you probably know how many questions you are going to ask, you can stick to the array if you like and make it exactly as long as the number of questions you have. I would like to see the first person who succeeds in answering more questions incorrect then the number of questions available on the test
Use a collection, like a List implementation (like ArrayList), instead of an array. Then you can add by calling list.add(miss) and never worry about the size.
Do you specifically need an array? You can get the array, but in general, it's rare to specifically need one for requirements like these.

Categories