How do I resolve this problem...
I wanna add object OrgDO in allOrgListArr[idx].
ArrayList<OrgDO>[] allOrgListArr = new ArrayList[Integer.parseInt(maxLv)+1];
for(int i = 0; i < Integer.parseInt(maxLv)+1; i++) {
allOrgListArr[i] = new ArrayList<OrgDO>();
}
for(OrgDO org : allOrgList.getOrgListList()) {
allOrgListArr[org.getORG_LEVEL()].add(org); // --> this part throws a NullPointerException
}
You need to be a bit more defensive in your programming and check that the index exists in the array and if so you also need to check that you have an object at that index
for(OrgDO org : allOrgList.getOrgListList()) {
int level = org.getORG_LEVEL();
if (level >= allOrgListArr.length()) {
continue; //or other error handling
}
List<OrgDO> list = allOrgListArr[level];
if (list == null) {
list = new ArrayList<OrgDO>();
allOrgListArr[level] = list;
}
list.add(org);
}
Related
I am trying to hand over the position value of my object 'next' to the next 'next' object. Is it possible to write this code as a loop and scale it by n?
next.next.next.next.pos.y = next.next.next.pos.y;
next.next.next.next.pos.x = next.next.next.pos.x;
next.next.next.pos.y = next.next.pos.y;
next.next.next.pos.x = next.next.pos.x;
next.next.pos.y = next.pos.y;
next.next.pos.x = next.pos.x;
next.pos.x = pos.x;
next.pos.y = pos.y;
I guess you want something like this:
while(obj.next != null) {
obj.next.pos.x = obj.pos.x;
obj.next.pos.y = obj.pos.y;
obj = obj.next;
}
Later edit:
Sorry, I misunderstood your question.
You could then use a list to solve this issue. It's not the most performant way to do it but I will work.
List<Obj> objs = new ArrayList<>();
objs.add(obj);
// Add everything to a list
while(obj.next != null) {
objs.add(obj.next);
obj = obj.next;
}
// Walk the list in the reverse order
for(i = objs.size() - 1; i > 1 ; i--) {
objs[i].pos.x = objs[i - 1].pos.x;
objs[i].pos.y = objs[i - 1].pos.y;
}
I have an issue while working with java ArrayList. Here is the brief description:
By making a web service call, I will get all the videos around 900+ as Java objects. These Java objects are lacking some of the required information. So I am again making a call to another web service by passing the video id. This also returns Java objects.
I am storing the first web service call values and the second web service call values into two different Java ArrayLists as below:
List mediaList = new ArrayList();
List mediaVOs = new ArrayList();
Finally I am writing a method by passing two lists and setting those values into one java object. This should return the total objects around 942. But this is returning some odd number 887364 instead of 942 count.
Please help me resolving the issue. Here is the code:
client = getClient();
if (client != null) {
List<MediaEntry> mediaList = getAllMedia();
if (mediaList.size() >= 1) {
System.out.println("Total Media ------>" + mediaList.size());
MetadataListResponse metadataListResponse = null;
Media mediaVO = null;
List<List<String>> metadataValues = new ArrayList<List<String>>();
List<String> categoriesList = new ArrayList<String>();
List<String> accountNamesList = new ArrayList<String>();
List<String> ownerNamesList = new ArrayList<String>();
List<String> countryList = new ArrayList<String>();
List<String> languageList = new ArrayList<String>();
for(MediaEntry entry:mediaList) {
if(entry != null) {
metadataListResponse = getMetadata(entry.id);
if (metadataListResponse.totalCount >= 1) {
mediaVO = new Media();
List<Metadata> metadataObjs = metadataListResponse.objects;
if (metadataObjs != null
&& metadataObjs.size() > 0) {
for (int i = 0; i < metadataObjs.size(); i++) {
Metadata metadata = metadataObjs
.get(i);
if (metadata != null) {
if (metadata.xml != null) {
metadataValues = parseXml(metadata.xml);
if (metadataValues.size() != 0) {
categoriesList = metadataValues
.get(0);
accountNamesList = metadataValues.get(1);
ownerNamesList = metadataValues.get(2);
countryList = metadataValues.get(3);
languageList = metadataValues.get(4);
if (categoriesList.size() == 1) {
for (String categoryName : categoriesList) {
//System.out
//.println("categoryName"+categoryName);
mediaVO.setCategories(categoryName);
}
}
if (accountNamesList.size() == 1) {
for (String accountName : accountNamesList) {
//System.out
//.println("accountName"+accountName);
mediaVO.setAccountName(accountName);
}
}
if (ownerNamesList.size() == 1) {
for (String ownerName : ownerNamesList) {
//System.out
//.println("ownerName"+ownerName);
mediaVO.setOwnerName(ownerName);
}
}
if (countryList.size() == 1) {
for (String country : countryList) {
//System.out
//.println("country"+country);
mediaVO.setCountry(country);
}
}
if (languageList.size() == 1) {
for (String language : languageList) {
//System.out
//.println("language"+language);
mediaVO.setLanguage(language);
}
}
}
}
}
}
}
}
mediaVOs.add(mediaVO);
}
}
System.out.println("mediaVOs.size()------>"+mediaVOs.size());
List<Media> medias = setMediaVO(mediaList, mediaVOs);
if(medias.size() >= 1) {
System.out.println("Final medias size ------>"+medias.size());
mediaXml = convertToXml(medias);
System.out.println("Final Media XML converted ------->"+mediaXml);
Document doc = convertStrToDoc(mediaXml);
}
}
}
private List<Media> setMediaVO(List<MediaEntry> mediaList,List<Media> mediaList1) {
if(mediaList.size() >= 1) {
if(mediaList1.size() >= 1) {
for(MediaEntry media:mediaList) {
for(Media media1:mediaList1) {
Media mediaVO = new Media();
MediaType mediaType = media.mediaType;
mediaVO.setMediaId(media.id);
mediaVO.setMediaName(media.name);
mediaVO.setMediaDesc(media.description);
mediaVO.setCreatedDate(media.createdAt);
mediaVO.setCreditUserName(media.creditUserName);
mediaVO.setDataUrl(media.dataUrl);
mediaVO.setDownloadUrl(media.dataUrl);
mediaVO.setDuration(media.duration);
mediaVO.setEndDate(media.endDate);
mediaVO.setEntitledUsersEdit(media.entitledUsersEdit);
mediaVO.setEntitledUsersPublish(media.entitledUsersPublish);
mediaVO.setLastPlayedAt(media.lastPlayedAt);
mediaVO.setMediaType(mediaType.toString());
mediaVO.setUpdatedDate(media.updatedAt);
mediaVO.setPlays(media.plays);
mediaVO.setViews(media.views);
mediaVO.setCategories(media1.getCategories());
mediaVO.setAccountName(media1.getAccountName());
mediaVO.setOwnerName(media1.getOwnerName());
mediaVO.setCountry(media1.getCountry());
mediaVO.setLanguage(media1.getLanguage());
medias.add(mediaVO);
}
}
}
}
return medias;
}
Thanks,
Raji
Your problem is here :
for(MediaEntry media:mediaList) {
for(Media media1:mediaList1) {
For each MediaEntry, you're looping on each Media, which means you'll execute the code inside 942 * 942 times, while what you want is to execute it 942 times. You've got to match MediaEntries with Media and execute the code once.
Let me try to explain this in a way where everybody understands what i mean.
The problem is indeed the fact that you multiply 942 by itself.
This happens cause of the following code:
private List<Media> setMediaVO(List<MediaEntry> mediaList,List<Media> mediaList1) {
if(mediaList.size() >= 1) {
if(mediaList1.size() >= 1) {
for(MediaEntry media:mediaList) {
for(Media media1:mediaList1) {
//Do stuff
}
}
}
}
return medias;
}
Here you loop though medialist 1 for each item in medialist and do stuff with it.
At the end of this code you add each entry found in medialist 1 to a other list but this happend 942 times per item in the first list.
And since that list has 942 items you get the "odd" number of 887.364.
I made a method which finds a value in my ArrayList. I also copied this method so I could use it for my array but certain things such as the get and size don't work. I'm unsure how I'm supposed to restructure it.
public Product findProduct(String givenProduct) throws IllegalProductCodeException {
IllegalProductCodeException notFoundMessage
= new IllegalProductCodeException("Product was not found");
int size = rangeOfProducts.length;
int i = 0;
boolean productFound = false;
while (!productFound && i < size) { //While book hasn't been found and i is less than the size of the array
productFound = rangeOfProducts.get(i).getProductCode().equals(givenProduct);
//Checks whether the given value in the array's reference is equal to the given reference entered
i++; //if not then add 1
}
if (productFound) {
return rangeOfProducts.get(i - 1);
} else {
throw notFoundMessage;
}
}
The array alternative to .get(i) will be [i] and the alternative to .size() will be .length.
for (Product product : products) {
if (product.getProductCode().equals(givenProduct)) {
return product;
}
}
throw new IllegalProductCodeException("Product was not found");
Edit: Java 5's enhanced for loop is equivalent to
for (Iterator<Product> iter=products.iterator(); iter.hasNext(); ) {
Product product = iter.next();
Using this code
System.out.println("New Mark Entry\n--------------" + "\n\nEnter the description (up to 40 characters will be displayed):");
name = TextIO.getlnString();
if (name.length() > 40) {
name = name.substring(0,40);
}
System.out.println("What was the assignment out of?");
totalMark = TextIO.getlnDouble();
System.out.println("What was the students mark?");
mark = TextIO.getlnDouble();
System.out.println("What was the weight of this assignement?");
weight = TextIO.getlnDouble();
input = 1;
int openSpot = 0;
for(int i = 0; i < markbook.length; i++) {
if(markbook[i].getAssignment(name) == null) { // java.lang.NullPointerException is thrown here
openSpot = i;
break;
}
}
markbook[openSpot] = new Mark(name, totalMark, mark, weight);
break;
Causes a java.lang.NullPointerException to be thrown. Im a tad confused at what to do to fix this. If anyone could help or point me in the right direction it would be greatly appreicated
you are initializing markbook after and trying to use it before
for(int i = 0; i < markbook.length; i++) {
if(markbook[i].getAssignment(name) == null) { // java.lang.NullPointerException is thrown here
openSpot = i;
break;
}
}
markbook[openSpot] = new Mark(name, totalMark, mark, weight);//you are initializing markbook after and trying to use it before
it should be like following
//initialize first
markbook[openSpot] = new Mark(name, totalMark, mark, weight);
//use later
for(int i = 0; i < markbook.length; i++) {
if(markbook[i].getAssignment(name) == null) { // java.lang.NullPointerException is thrown here
openSpot = i;
break;
}
}
If the NPE happens on that exact line, the most likely cause is that markbook[i] is null. You don't show how you've initialised it, but in addition to allocating the array you also need to create the elements.
For an example, see https://stackoverflow.com/a/10044418/367273
I would look at the line where the NullPointerException has been throw.
Let say it is
markbook[i].getAssignment(name)
Then I would check that I actually set markbook[i] to something, because otherwise it will be null.
Note: this is not enough.
MyType[] markbook = new MyType[4];
as this is the same as
MyType[] markbook = { null, null, null, null };
If it still doesn't make sense, I would use a debugger to debug your code.
I'm trying to implement a dictionary with a hash table (not using Java's provided hash table classes, but rather made from scratch). Below is the find() method from my Dictionary class, used to detect whether or not a key is in the table when inserting/removing. If the key is already in the table, it returns a score associated with the key (elements in the table are inserted as pairs of key/score into LinkedLists in each table position). If not, it returns -1.
I am running a supplied test program to determine if my Dictionary class works, but I am encountering a NullPointerException when reaching a certain point. Included below is the particular test. Why would this exception be coming up? (I can provide more code if needed!)
Find:
public int find(String config) {
for (int i = 0; i < dictSize; i++) {
if (dict[i] != null) {
LinkedList<DictEntry> current = dict[i];
String currentConfig = current.peek().getConfig(); //Dictionary.java:66
if (currentConfig.equals(config)) {
int currentScore = current.peek().getScore();
return currentScore;
}
}
}
return -1;
}
Insert:
public int insert(DictEntry pair) throws DictionaryException {
String entryConfig = pair.getConfig();
int found = find(entryConfig); //Dictionary.java:27
if (found != -1) {
throw new DictionaryException("Pair already in dictionary.");
}
int entryPosition = hash(entryConfig);
if (dict[entryPosition] == null) { //Dictionary.java:35
LinkedList<DictEntry> list = new LinkedList<DictEntry>();
dict[entryPosition] = list;
list.add(pair);
return 0;
} else {
LinkedList<DictEntry> list = dict[entryPosition];
list.addLast(pair);
return 1;
}
}
The test:
// Test 7: insert 10000 different values into the Dictionary
// NOTE: Dictionary is of size 9901
try {
for (int i = 0; i < 10000; ++i) {
s = (new Integer(i)).toString();
for (int j = 0; j < 5; ++j) s += s;
collisions += dict.insert(new DictEntry(s,i)); //TestDict.java:69
}
System.out.println(" Test 7 succeeded");
} catch (DictionaryException e) {
System.out.println("***Test 7 failed");
}
Exception stack trace:
Exception in thread "main" java.lang.NullPointerException
at Dictionary.find(Dictionary.java:66)
at Dictionary.insert(Dictionary.java:27)
at TestDict.main(TestDict.java:69)
peek() returns null that's why. You can have a nullity check prior to getConfig() call.