linked list throws an IndexOutOfBoundsException - java

I have a piece of code which involve a LinkedList. The followings
topic.read()
topic.delete() and
topic.send()
are methods from that LinkedList called Topic. These are being implemented in a GUI design. The methods
topic.read(name)
topic.send(text)
are working OK, but the
topic.delete(index)
is throwing me an
IndexOutOfBoundsException
I explain the methods briefly:read(name) and send(text) take String parameters and reads the topics and its list of messages and sends messages to topics receptively. The delete(index) should delete the index-specified message from the topic. However, the error message is telling me that the Size is 0.
The relevant piece:(I reckon that the piece should be enough, if needed more pieces will be added)
public void act(String s)
{
topic = new Topic(s, topics);
if (s.equals("Read"))
setEditorText(topic.read(readText()));
else if (s.equals("Delete"))
topic.delete(indexText());
else if (s.equals("Send"))
{
topic.send(getEditorText(), sendText());
clear();
}
}
Added these to this Quesion:
private JTextField indexText = new JTextField(10);
public int indexText()
{
return Integer.parseInt(indexText.getText());
}
public class Topic {
private LinkedList<String> messages = new LinkedList<String>();
public void delete(int index)
{
messages.remove(index - 1);
}
}

You need to do bounds checking then, if the index is valid, before deleting, such as:
if (index > 0 && index <= messages.size()) {
messages.remove(index - 1)
};
This will allow you to avoid IndexOutOfBoundsException

Hello Dilshat Abduwalli!
When you are getting a response that say your index size is 0 means that objects are not being added to the list or haven't yet been added and is why you go to delete said object of index value 2 for example it is going to throw an IndexOutOfBoundsException since the index is size is only 0. Ensure that you are adding values to your List or otherwise it will not be populated.
I would reccomend using #nitegazer2003 if statement you check for values that will fit within your List.size() you a integer isn't called that exceeds the List size which will give you the IndexOutOfBoundsException.
Double check your list values with a for loop.
for(int i = 0; i < list.size(); i++)
System.out.println(list.get(i)); //Print the Strings in the list (Assuming its a list of Strings)
Or
for(int i = 0; i < list.size(); i++)
System.out.println(list.getSize()); //Test the size of the list
Simular Question about Index 0 and OutOfBoundsException
The last posted response explains a similar answer. You don't have to read all his code though.
Oracle's List
Good source for documentation of List and its features.
I hope this helps or points you in the right direction! Good Luck!

Related

Java: How to use Deque's?

https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html
I am learning about to how use this object.
boolean add(E e)
Inserts the specified element into the queue represented by this deque
(in other words, at the tail of this deque) if it is possible to do so
immediately without violating capacity restrictions, returning true
upon success and throwing an IllegalStateException if no space is
currently available.
I am confused on 'if no space is currently available.' I don't see anything where you set the size, does it mean No space as in, no JVM?
I am looking into how to make a Deque that holds 5 values and I want to add one and remove the oldest when it is at 5.
I hope this makes sense, if not please ask me to elaborate and I will.
Thanks a lot SOF community!
This is how I would do it with a Deque - it's simple but I think it addresses the problem you are trying to solve.
public class DequeExample {
Deque<Integer> deque = new ArrayDeque<>();
public static void main(String[] args) {
DequeExample dequeExample = new DequeExample();
// adding elements
for( int idx = 0; idx < 9; idx++){
dequeExample.addNewest(idx);
}
}
private void addNewest(int newest){
if(deque.size() == 5){
System.out.println("Queue at capacity, removing element before adding more.");
Integer e = deque.removeLast();
System.out.println("Removed: " + e);
}
deque.push(newest);
System.out.println("Added: " + newest );
System.out.println(deque);
}
}
How to use Deque (and then its just about wrapping this to methods you wish to support with few if statements):
Deque<String> deq = new LinkedList<>(); //to have a fixed size, use ArrayDeque<E>
deq.addFirst("a");
System.out.println(deq.peekFirst()); //a - just take a look, do not remove
deq.addFirst("b");
System.out.println(deq.peekFirst()); //b
System.out.println(deq.peekLast()); //a
deq.addLast("c");
System.out.println(deq.peekLast()); //c
deq.add("d");
System.out.println(deq.peekLast()); //d
System.out.println(deq.pollLast()); //d - return and remove
System.out.println(deq.pollLast()); //c
If you want to have some kind of circular buffer, you may want to use this Apache Commons collection instead - CircularFifoBuffer

Java, return a linkedlist from a linkedlist parameter

I am trying to create a method which returns the place values of any two digits in a list that sum to zero. Where I am getting stuck is: creating the return method type, choosing the appropriate parameter to pass, and creating an empty list which holds the values to return.
Any help would be greatly appreciated!!
public class TwoSums {
public LinkedList<Integer> sum_values(LinkedList<Integer> input){
(Above) I am trying (but not sure how) to return a linked list from the method. I want the parameter to be a list with values like {3,-3,0,1}. I am also unsure of what the return type should be here.
int iterator = 0;
int scanner = 0;
LinkedList positions = new LinkedList<Integer>();
(Above) I am trying to create an empty list which I can push the place values of the parameter into, if they sum to zero
while(iterator<input.length){
if (iterator + scanner !=0){
scanner ++;}
else if (iterator + scanner ==0){
//push iterator and scanner values to the linkedlist
This is probably your homework, so I will just give you some guiding thoughts; I wont do the work for you!
First of all, the return type. Thing is: you can't just return single numbers. Because, you are interested in pairs of numbers. Thus you need some class like
public class IndexPair {
private final int firstIndex;
private final int secondIndex;
public IndexPair(int first, int second) { this.firstIndex = first ...
and then your method can simply return a List<IndexPair> object. Note: if you are serious here, you would want to override the equals method for example; in order to allow for easy comparison of IndexPair objects.
And of course: Java already knows some Pair classes which could be used here; instead of inventing your own thing.
The other problem: finding those pairs. A naive solution would be:
List<IndexPair> results = new ArrayList<>();
for (int firstIndex = 0; firstIndex < input.size(); firstIndex++) {
for (int secondIndex = firstIndex+1; secondIndex < input.size(); secondIndex++) {
if (input.get(firstIndex) + input.get(secondIndex) == 0) {
results.add(new IndexPair(firstIndex, secondIndex));
As said; the above is meant to get you going. There might be some typos or subtle bugs in that code. Take it as inspiration and work with it until it does what you need!
Edit: calling your method is as as
List<IndexPair> pairs = sum_values(Arrays.asList(-3, 3, 0, 0))
for example. But please understand: that is really basic stuff. Just do some reading around Lists and arrays. Those things have been documented many many times.

How to test for an index being out of range of array of Objects (Object[]) in Java?

I am making an implementation of the ArrayList class from scratch, using just Object[] and the standard functions. I'm trying to make a "size" method, which returns an int that is the size of the Object[] array.
public class MyArraryList{
Object[] Objects = new Object[0];
public int sizeOf(Object[] o)
{
int i = 1;
while(i > 0)
{
if()
}
}
This is what I have so far. In the if statement, I essentially want to check if there's an error along the lines of "index out of range of array". I'm not sure what the syntax for this is. Can someone explain how to do this please? thanks!
You can find the length of an array using
objects.length
It would be possible to write a version of ArrayList where the length of the array is always equal to the size of the list. In this case the size method would just be
public int size() {
return objects.length;
}
Such a list would be very slow. Because arrays are fixed-length, you would have to create a new array on every addition or removal for this to work.
ArrayList does not work like this. An ArrayList has 2 fields; an Object[] and an int called size. The point is that the length of the array is often higher than the size of the list, because there are unused slots at the end of the array. If you do it this way the size method is just
public int size() {
return size;
}
The most useful thing you can do is read the source code for ArrayList to see how it works.
I essentially want to check if there's an error along the lines of "index out of range of array"
You can find the length of an array like this:
int length = 0;
try {
while (true) {
Object o = objects[length];
length++;
}
} catch (ArrayIndexOutOfBoundsException e) {
// ignore
}
However you should not use exceptions in such a way. They should be reserved for genuinely exceptional situations.
you could use a try catch with ArrayIndexOutOfBoundsException e, which was made for these kinds of instances.
http://www.tutorialspoint.com/javaexamples/exception_multiple1.htm

Remove item from ArrayList issue

I'm writing a class that have a method of removing an object from other class. But it just worked inproperly, the output is not correct. Please help me through, and is there any better solution for this, I think my solution is quite cumbersome. Here is my code:
public List<Task> getTaskDue(){
List<Task> temp = this.taskCollection;
for (int unit = 0; unit < this.unitCollection.size(); unit++){
for (int j = 0; j < this.unitCollection.get(unit).getAssessmentCollection().size(); j++){
for (int i = 0; i < temp.size(); i++){
if (temp.get(i).getDueDate().compareTo(this.unitCollection.get(unit).getAssessmentCollection().get(j).getDueDate()) > 0)
temp.remove(i);
}
}
}
return temp;
}
Updated: I have Diary class that has list of Task class and Assessment class that hold due date attribute. I want to create a method that return a new list which have a list of over due task by comparing the task from diary class with the due date attribute from assessment class. The program compile successfully but the result is not correct if I want to test the list return no task item since no task is over due.
It seems like "removing" elements from the list isn't your ultimate problem.
You said you want your method to return a new list that contains elements from taskCollection based on some criteria. At the same time, I don't think you want to destroy or change taskCollection in any way.
So instead of creating temp as a reference to taskCollection, have it be a new ArrayList<Task>() instead. Then add tasks to temp (the new list) that you want to ultimately return from your method.
I am going to leave my adivce at that, because your code sample, in isolation, has a lot of unknowns that prohibit me from making any educated guesses on what you really need it to do.
Also, there are too many for loops! (I'm mostly kidding, but seriously...)
With more information from the comments below, I've modified your code to implement what I am suggesting. In order to add the items to temp (instead of remove them) I had to change your if statement from > 0 to <= 0. Also, instead of iterating over taskCollection in the inner-most loop, you should get tha tasks from the current assessment and iterate over those.
public List<Task> getTaskDue(){
List<Task> temp = new ArrayList<Task>();
for(int u = 0; u < unitCollection.size(); u++){
Unit unit = unitCollection.get(u);
for (int a = 0; a < unit.getAssessmentCollection().size(); a++){
AssessmentItem assessment = unit.getAssessmentCollection().get(a);
for (int t = 0; t < assessment.getTasks().size(); t++){
Task task = assessment.getTasks().get(t);
if (task.getDueDate().compareTo(assessment.getDueDate()) <= 0){
temp.add(task);
}
}
}
}
return temp;
}
If you need to alter a list as you're iterating through it, use a ListIterator. Call listIterator() on your list to create one, then see relevant methods on ListIterator.
You are removing an object from an index but index in iteration is not altered. Due to the reason you would be skipping an element in the list. Perhaps that is the reason why your results are not correct.
Change:
if ( temp.get( i ).getDueDate().compareTo( this.unitCollection.get( unit )
.getAssessmentCollection().get( j ).getDueDate() ) > 0 )
temp.remove(i);
to:
if ( temp.get( i ).getDueDate().compareTo( this.unitCollection.get( unit )
.getAssessmentCollection().get( j ).getDueDate() ) > 0 )
{
temp.remove(i);
i--;
}
PS: Better always practice using flower braces irrespective of number of statements under the condition or loop.

Java BucketSort

I'm sure you probably get this a lot from CompSci students, I tried searching but mine looked a lot different from anything else I could find. Anyway, here is my class, it is supposed to sort an array of integers (then in the future be modified to sort objects, but ints will do for now).
My goal is to make an arrayList which is basically a row of buckets. then each bucket is a linked list. I feel like I'm on the right track, but the compiler doesn't like my last line of code, so I've run out of ideas.
here's an update. this is what I have now, but I still don't think it'll work
public void sorter(){
int highest_int = 0;
for(int i=0; i<entries.length; i++){
if (highest_int < entries[i])
highest_int = entries[i];
}
ArrayList<LinkedList<Integer>> row = new ArrayList<LinkedList<Integer>>();
LinkedList<Integer> column = new LinkedList<Integer>();
while (highest_int>0){
row.add(column);
highest_int--;
}
for(int i=0; i<entries.length; i++){
int j = entries[i];
column.add(0, j);
row.set(j, column);
}
}
The compiler "doesn't like" your code because the add() method of LinkedList doesn't return anything (has void return type). Therefore it cannot be used as an argument to the set() method. Basically, add() modified the object that it is called on, but doesn't return that object as a value.
The simplest change I can suggest that I think will make your code compile would be:
for(int i=0; i<entries.length; i++){
int j = entries[i];
column.add(0, j);
row.set(j, column);
}
Beyond that, it's not clear to me what you are actually trying to accomplish here. I don't see anything that looks like a sort at all.
The compile problem is that column.add() returns void.
A bigger problem is that the same LinkedList is used for each bucket. You need to create a new LinkedList in each iteration of one of the for loops.

Categories

Resources