for(int m=0; m< checkBoxValue.length ; m++)
{
System.out.println("check box in model class"+checkBoxValue[m]+"\n");
}
This loop is to print two values in array. It prints the values But after that it shows array out of bound exception
It seems you're on the wrong track. It's best to set a breaking point on your for loop and debug your code, then go through it step wise. This will reveal where the exception is thrown...
Especially since you say "after that", you might want to review your code after that for loop :-)
Are you sure the Exception is raised here ?
Ohh.. Looks like a mess. The information looks very abstract. You need to be specific, may be you can give more code over here. One possible cause I think of, may be, is Multi-threading.
Only multi-threaded application can do this trick. If so, you better provide synchronization on the origin object of checkBoxValue variable.
Hope that helps....
The code should work fine provided you have done the array initialization correctly.
The posted code should not throw ArrayIndexOutOfBoundsException. Most likely, you are doing something after the loop which accesses an incorrect index of an array.
The only way that the code shown in the question could throw an ArrayIndexOutOfBoundsException is if the toString() method of one of the checkBoxValue[m] objects throws the exception.
Maybe you have overridden the toString() method of the checkBoxValue-class (the array initializer would help identifying this class). Following this theory, the toString() implementation might work fine for the first two elements of the array (they are printed) and may throw an exception for the third element in the array.
This could lead to the error description: This loop is to print two values in array. It prints the values But after that it shows array out of bound exception
Related
I'm trying to figure out what this is actually called and where I can find the answer for it. I can't understand the difference in
for (Treet treet : treets) { }
I don't know what the different "treet" mean. can someone help me or at least tell me what it's called?
for (Treet treet : treets) { }
This is an enhanced for statement (although often referred to as an enhanced for loop). You are saying that you want to do something for every element in some collection of things. (Well, actually, you're doing nothing here, but never mind).
In English: "For every Treet in treets, do something".
Treet is a type. Somewhere you need a class called Treet defined. If it's in a different package, you need to import it.
treets is either an Iterable<? extends Treet>, meaning you could call treets.iterator() and use the result in the standard hasNext()/next() way; or an array of something which extends Treet. It's something you can iterate through.
treet is a single element from the iterable/array. You can use it only inside the body of the loop.
Thats a forach loop, it iterates through the array/list/... and performs the actions defined in the loop to every element in the list which is referenced by treet.
I am reading the code of Hashtable and am confused and have some questions.
I coded like this:
Hashtable table = new Hashtable();
table.put(table, 1);
int code = table.hashCode();
I have two questions:
When I invoke the hashCode method just like the third line code, why isn't it an endless loop? I think it is an endless loop.
When I debug this code, I found that code new Hashtable() will cause the invocation of put method, why?
According to the OpenJDK source I'm reading, there's a guard written specifically to guard against the case where a Hashtable contains itself.
I don't see any reference to put within the constructor. Do you have a trace you could post in your answer?
First off, use a hashmap as it's better in many cases.
Second, this uses Oracle's implementation.
It's not an infinite loop. HashTable.hashCode( simply iterates through the map's elements once. Not infinitely. Unless the table contains itself, where in the source I found it is indeed very hacky but does prevent the recursion. In that case it skips calculating its own hash code returning 0.
Looking at the source, no put( is called. Only the next line calls Put.
I've got a very strange error, that would like to share with you.
I've the following code (simplified):
public ArrayList<String> al = new ArrayList<String>();
public void doSomething() {
int size = al.size();
for(int i=0; i<size; i++) {
if (al.get(i) != null) {
System.out.println(al.get(i));
String sPath = al.get(i);
File fFile = new File(sPath);
fFile.delete(); // Simplified. It has some error checking
}
}
}
I have one error, saw in the production environment:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MYCLASS.soSomething(MICLASS.java:1944)
[...]
Line 1944 is if (al.get(i) != null) {.
What! How can it raise IndexOutOfBound?!
The problem is that the error does not reproduce. I've been able to raise it only once in the dev environment, but trying to reproduce it was not possible (it dit not raise again)... so no way to look for a pattern in the error.
So my only option is simple: read the code and use the brain.
So I browse the code of java.util.ArrayList.get():
public class ArrayList<E> [...]{
public E get(int index) {
RangeCheck(index);
return (E) elementData[index];
}
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
}
}
So it throws the exception because index >= size... How is it possible? The for() sweeps from 0 to size-1... It is impossible! It cannot raise the error!
Wait a second! This code is not thread-safe. Maybe another thread is calling clear() or remove*() on the ArrayList... Studying the code, it is not possible. So I run it, set a breakpoint on line 1944 and watch the threads in that moment, and effectively, the other running threads have nothing to do with this issue.
Any other clue?
Kernnigan & Pike: "Debugging [...]Something impossible occurred, and the only solid information is that it really did occur."
I see the following candidates how this happens:
something in your loop changes the value of i.
something in your loop changes the size of al, possibly something removing elements.
something is replacing your collection with a different collection.
I have seen cases where the loop was constructed in a way so the body gets even executed once in the case of an empty collection. Although that seems unlikely with a for loop as described.
An idea for debugging this: replace the list with your own implementation which logs every access to it, and delegating all the real functionality to a standard implementation.
If needed it can print the stack trace of an freshly created exception in order to identify the place it is called from. It can even throw an exception when it gets accessed from a different thread.
Everyone is suggesting that you're removing elements from the Array. The solution to your problem is to use an Iterator, which allows you to iterate through an entire Collection, but still allow you to modify that Collection.
You probably remove elements from your ArrayList in your for loop, therefore decrementing its original size which is used to exit this loop!
How sure are you that your simplified code exactly replicates the production code? To my mind it's impossible for your simplified code to raise IndexOutOfBoundsException because the list is empty so the for loop should never be processed. Are you modifying the contents of the array list in the loop?
Another possibility is that another thread is modifying the list while your code above is scanning it.
If you want something better than guesses, you need to show us either the relevant production code, or create a simplified version that actually exhibits the same problem when you run it.
Studying the code, it is not possible.
Clearly is is possible, otherwise you wouldn't have observed it.
Thanks everybody for the answers. Most of the suggestions are based on:
A) The loop is modifying al or i.
B) Another thread is modifying al.
c) Another thread is replacing al.
Since I know A is not the case, I'll bet that in some cases another thread is modifying/replacing al. Since I cannot make it fail in a pattern, such thread may be running only in certain situations, such as error conditions. While the code in the loop is pretty simple, the application is not at all small, with abuse of singletons and getter/setters, and it hardens the debugging, so I wouldn't be surprised of it.
That's the same that I suspected (except C, that I had not though of), but you confirmed that this is the only possible cause. Thanks for your help.
I've been at this one for a bit now.
I've got a null pointer exception so I'm guessing somethings not been initialized.
AdminMessages.inbox1.setText(messageRsetArray[0]);
That's my code where it's targetting. But I can't find what's inside. It hasn't been
initialized.
AdminMessages is a class which contains a JTextField called inbox1, messageRsetArray is an array which has taken variables from an array.
Also inbox1 is static. I couldn't get the getters and setter to work. I know it's bad practice though.
Exception in thread "main" java.lang.NullPointerException
at project.AdminMessages.fillInboxGui(AdminMessages.java:587)
at project.AdminMessages.<init>(AdminMessages.java:156)
at project.AdminUser.createAdminMessages(AdminUser.java:31)
at project.AdminUser.<init>(AdminUser.java:17)
at project.AdminUser.main(AdminUser.java:45)
inbox1 and/or messageRsetArray are null. You have to instantiate them using:
inbox1 = new JTextField();
and
messageRsetArray = new String[size];
In such cases simply check which of the variables can possibly be null at that location. If you cannot tell for sure, then split the expression so that there is only one "NPE-thrower" per line:
String text = messageRsetArray[0];
AdminMessages.inbox1.setText(text);
And you will have your definitive answer in the next stacktrace.
To the best of my knowledge what you want cannot be easily done (ANY "dot" is a candidate for the exception).
A slight rewrite of the source code may be the easiest way to get what you need.
AdminMessages.inbox1.setText(messageRsetArray[0]);
into
inbox1 = Adminmessages.inbox1;
text = messageRSetArray[0];
inbox1.setText(text);
This leaves you with only one "dot" operation per line, and makes it obvious which one is broken.
You may also want to help the person to see the stacktrace with a
if (AdminMessages.inbox1 == null) {
throw new IllegalArgumentException("AdminMessages.inbox1 == null");
}
(I like this for method arguments. When inside code you may want NullPointerExceptions instead).
set a debugger breakpoint and print out the values of the various candidates.
make some local variables so that only one thing can be null at a time.
The quickest and easiest way: use a debugger.
And in general:
Try to avoid null values by setting everything to useful default values if possible
Try to avoid chaining method calls and property accesses like that
I have the following code:
Map<String, ObjectType> objectMap = new HashMap<String, ObjectType>();
for (ObjectType obj : objects) {
obj.setSomeProperty("property value");
objectMap.put(obj.getADiffProperty(), obj);
}
It seems like during loop iteration some of the obj property changes for different keys than the one currently being set. Is there a problem with the above code? Somehow the reference to obj is being recycled by the for loop?
Also this loop is in an outer loop as well.
Update:
I am providing the full method below. The actual place where I am observing the behavior described above is in the outer map defined as Map<String, Map<String, GlossaryTerm>> loadedTerms = new HashMap<String, Map<String, GlossaryTerm>>(); defined in a Singleton class.
List<Audience> audiences = ContentAccess.getAudienceList();
List<GlossaryTerm> glossaryTerms = ContentAccess.getAllReplacementCIs();
for (Audience audience : audiences) {
Map<String, GlossaryTerm> termMap = new HashMap<String, GlossaryTerm>();
for (GlossaryTerm term : glossaryTerms) {
String definition = term.getProductGlossary().get(audience.getName());
if (definition != null)
term.setDefinition(definition);
termMap.put(term.getPhrase(), term);
}
loadedTerms.put(audience.getChannelId(), termMap);
}
I don't think what you think is happening, is happening. The object reference is what it's supposed to be, for each iteration. I think something else must be happening - that the properties are changing elsewhere, or don't have the values you think they have initially. Put in some printlns to track down what's really going on. The code you've shown can't be changing the wrong properties.
It seems like during loop iteration some of the obj property changes for different keys than the one currently being set. Is there a problem with the above code? Somehow the reference to obj is being recycled by the for loop?
The obj variable will be set to the "next" element of the iterator for objects each time around the loop. If you see the same reference value in obj more than once it can only be because:
the reference value genuinely appears more than once in collection, array or whatever given by objects, or
something in setSomeProperty or getADiffProperty or something else you are doing in the loop is updating objects as a side-effect, or
the objects object has a buggy iterator implementation.
Another possibility is that what you are seeing is different objects with the same adiff values.
To say anything more, I'd need to see more source-code than the simplified snippet you have provided.
EDIT - the extra code you provided has not revealed the problem. (I think we can dismiss any theories involving updating the lists while they are being iterated, or strange side-effects from the setters.)
My suspicion is that one of those lists that the singleton is providing contains duplicates or something else unexpected. It could be that is what is causing your problem.
Do what #Carl suggests and use traceprints and/or a debugger to figure out what is in the Collection singleton and what your code is actually doing.
EDIT 2 - The fact that the collection thingy is a singleton class is probably irrelevant. And the contents of a HashMap DO NOT change randomly or spontaneously. (And there are no little green demons in your code that conspire to make it fail. Trust me on this!)
You seem to have the mindsight of guessing what the problem is and making changes based on those guesses in the hope that they will fix the problem. STOP GUESSING! That is the wrong approach, and will probably only make things worse. What you need to do is debug the code carefully and methodically, gathering hard evidence of what your program is actually doing, and interpreting that evidence carefully ... without resorting to crazy notions that something is changing things randomly.
EDIT 3 - If I was in your situation, I would ask another experienced Java programmer in the team to sit down with me and help me debug the code. I still occasionally need to do this myself, and I've had 10 years+ Java experience and 30+ years programming experience. Sometimes you get a mental block on a problem, and a fresh mind / fresh approach is the answer.
It is not a shameful thing to admit to your team / boss that you are out of your depth and need help.
I'm starting a new answer because - well, it's a new thought here, and the discussion thread was getting rather long.
You haven't (I think) said when the changes happen. But you are (potentially) putting the same term into multiple maps, for different audiences. Nothing to do with the loop variable - just that you are repeatedly using the same list of terms, for each audience. But when you put the term into a map, you also change its definition. But the definition is (potentially) different for each audience. So, concrete example:
Term A has the definition of "x" for audience X, and "y" for audience Y. You have both audiences. Initially, we encounter audience X, so A gets definition "x". A gets added to the map for this audience. Now we iterate to the next audience, and change the definition for A to "y". This changes A everywhere you have a reference to it - including in the map for audience X. This would explain why making a copy eliminates the problem. Is this what you are experiencing?
This might be just a typo error. There is no object declared in your snippet, but your put call uses object.getADiffProperty() rather than obj.getADiffProperty(). Is that intentional?
From where the code is called? May be there are concurrent issues? Are there other threads (is it a webapp?) accessing ContentAccess? And I hope GlossaryTerm is a simple Dto, right?