I'm trying to access my ArrayList from my other class, through a Foreach-loop. But this doesn't seems to work, for some reason. No error, just simply won't execute the Foreach loop.
Heres my code:
for(Entity entity : world.entitys) {
if(entity.isMouseDown()) {
System.out.println("Touching Entity");
} else {
System.out.println("Is not Touching Entity");
}
}
Arraylist from World Class:
public ArrayList<Entity> entitys = new ArrayList<Entity>();
World is my other class. entitys is my Arraylist. Entity is my class for my entitys in the Arraylist.
If there is not compiler or runtime error thrown only reason per your description is that the ArrayList is empty...
Learn to debug, it will help you resolve this kind of problems without asking for anyone's help..
Related
I realize that variations of this question have been asked before, but I am having a uniquely difficult time figuring out how to complete the following task:
I have an object that looks something like this (please note, "Skill" and "Certification" are ENUMS):
Public Employee {
String name;
List<Skill> employableSkills = new ArrayList<>();
List<Certification> certifications = new ArrayList<>();
...
}
In another class, I've got a
List<Employee> listOfEmployees;
and I'm trying to loop through it like this:
// determine the total number of employees who know Java
int numberOfEmployeesWhoKnowJava = 0;
for (Employee employee : listOfEmployees) {
if (employee.employableSkills.contains( ?? )) {
numberOfEmployeesWhoKnowJava++;
}
I'm struggling to get the exact syntax on the if-statement. I have tried this:
if(employee.employableSkills.contains(Employee.EmployableSkills.JAVA)) {
but EmployableSkills in this string gets "cannot resolve symbol."
How should I loop through the List on each Employee object and check if it contains JAVA?
Edit: It turns out I was making a fundamental error. In OOP, it is best not to expose the data from one class to another class. Instead, I wrote getters in the Employee class, then called those getters from my other class. That way, the data in Employee is not directly exposed to the class that needed it.
Even if you get syntax right, the following code will have a bad complexity of order n - O(n).
if(employee.employableSkills.contains(Employee.EmployableSkills.JAVA)) {
Change you List to hash implementation of set
Set<Skill> employableSkills = new HashSet<>();
and now loop through the employees
int numberOfEmployeesWhoKnowJava = 0;
for (Employee employee : listOfEmployees) {
if (employee.employableSkills.contains(Skill.JAVA)) {
numberOfEmployeesWhoKnowJava++;
}
}
This will give a complexity of O(1) while looking skills
Your question is a little unclear, but if my interpretation is correct, try this:
if (employee.employableSkills.contains(Skill.JAVA))
This is my first attempt to implement Entity Component System in my project and I'm not sure how some of its mechanics works. For example do I remove an entity? Since all systems are using entities list throughout whole game loop, every attempt of deleting element of that list is condemned to ConcurrentModificationException. Going by this advice I've tried to setting some kind of "toRemove" flag for entities and look for it every time system iterate through list
public class DrawingSystem extends System {
public DrawingSystem(List<Entity> entityList) {
super(entityList);
}
public void update(Batch batch) {
for (Entity entity : entityList) {
removeIfNeccesarry(entity);
//code
}
}
public void removeIfNeccesarry(Entity entity){
if(entity.toRemove){
entityList.remove(entity);
}
}
}
but that didn't help getting rid of the exception. I'm sure there is a elegant solution to this problem since this design pattern is broadly used but I'm just not aware of it.
Check out iterators:
"Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics."
https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Iterator.html
Iterator<Entity> it = entityList.iterator();
while (it.hasNext()) {
Entity entity = it.next();
if (...) {
it.remove();
}
}
You could also store the indices of the entities to remove somewhere outside the list and then remove the dead entities in an extra step after the update/render.
This has the advantage that you do not miss entities in later steps of your update.
Edit: Added code.
I am working on a game project. So far so good, but i just stuck on ome basic thing and i cant find a solution and make it work properly. I decided to come here and ask you ppl of suggestions.
PROBLEM:
When the player comes to contact with a diamond, i suppose to remove the diamond from the level and from the arraylist containing all the objects in the world. What always happens i get an exception error message after remove() method called.
CODES:
1.Class with the list: EDIT_1
private ArrayList<AbstractObject> objects = new ArrayList<AbstractObject>();
public void removeObject(String name){
ArrayList<AbstractObject> newest = new ArrayList<AbstractObject>();
ListIterator<AbstractObject> delete=objects.listIterator();
while(delete.hasNext()){
if(name.equals(delete.next().getName())){
delete.remove();
}
else{
delete.previous();
newest.add(delete.next());
}
}
objects=newest;
}
2.Player class calling the removeObject method: EDIT_1
public void playerLogic(){
fallingDown();
for(AbstractObject object : this.getWorld().getListOfObjects()){ <--------ERROR HERE
if(this.intersects(object)){
if(object instanceof FinishZone && points>=getWorld().getDiamondCount()){
if(!(getWorld().getManager().isMoreLevels())){
getWorld().getMenu().openMenu(true);
}
else{
this.getWorld().getManager().nextLevel();
}
}
if(object instanceof Diamond){
points++;
this.getWorld().removeObject(object.getName());
}
}
}
}
ERROR:
Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at project.objects.characters.Player.playerLogic(Player.java:77)
at project.objects.characters.Player.update(Player.java:70)
at project.world.World.update(World.java:110)
at project.Main.update(Main.java:122)
at project.Main.run(Main.java:65)
at java.lang.Thread.run(Thread.java:745)
I checked up some examples of removing items from arraylist but i havent find the difference.
EDIT_1:
So i figured out how to do it but i always get the error. I edited the removeobject code block. This worked good with a neutral list that i created for testing. I put all the items which i dont want to delete into a new list than ovewritten the old arraylist with the newest one. It worked with no exception error. When i made the same with the game list i want to edit it thrown the same error.
Ill put there the render code too if maybe there is the problem...
public void render(Graphics g) {
if(menu.getChoice()==-1){
menu.render(g);
}
else if(menu.getChoice()==0){
g.setColor(Color.white);
for(AbstractObject tempObj : objects){
tempObj.render(g);
}
}
}
FIXED:
Ill changed the starting list is ListIterator instead of putting items in arrayList before adding it to ListIterator. All methods changed to iterate. Working fine :)
You can't remove object while iterating over a list.
One option - use iterator.remove() - if you iterate with iterator, not the "enhanced for loop". You'll need to slightly modify your loop code, but the functionality will be the same.
Another: Store all objects to remove in an auxiliary list, and remove them all at the end of the loop.
I'm writing a program as part of tutorial for a beginner Java student. I have the following method and whenever I run it, it gives me the following exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Warehouse.receive(Warehouse.java:48)
at MainClass.main(MainClass.java:13)
Here's the method itself, within the class Warehouse:
public void receive(MusicMedia product, int quantity) {
if ( myCatalog.size() != 0) { // Checks if the catalog is empty
// if the catalog is NOT empty, it will run through looking to find
// similar products and add the new product if there are none
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
} else { // if the catalog is empty, just add the product
myCatalog.add(product);
}
}
The problem seems to be with the if else statement. If I don't include the if else, then the program will run, although it won't work properly because the loop won't iterate through an empty ArrayList.
I've tried adding a product just to keep it from being empty in other parts of the code, but it still gives me the same error. Any ideas?
You can't be iterating through the same list you're going to add things to. Keep a separate list of the things you're going to add, then add them all at the end.
You must not modify mCatalog while you're iterating over it. You're adding an element to it in this loop:
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
See ConcurrentModificationException and modCount in AbstractList.
we are assigned to implement the inside of a code block wherein it is associated with a given class (EmployeeProjectDetail) which is declared as a arraylist.
my code follows below.
public List<EmployeeProjectDetail> getEmployeeProjectHistory(long employeeID, long projectID) {
List<EmployeeProjectDetail> detailList = new ArrayList<EmployeeProjectDetail>();
return detailList;
}
I tried inputting the statements.
detailList.contains(projectDAO.getEmployeeProjects(employeeID));
detailList.contains(projectDAO.getEmployeeProjectRoles(employeeID, projectID));
the code then doesn't return any value but the invovled sql queries in projectDAO class are thoroughly handled. any help will be appreciated.
contains checks whether an item is in a list what your are looking for is add.
You should add the line
detailList.add(projectDAO.getEmployeeProjects(employeeID));
Update (I'm guessing on the method and class names)
Based on the ClassCastException it appears that getEmployeeProjects(employeeID) returns an ArrayList. If the objects in this ArrayList are EmployeeProjectDetail's you can just replace the method body with return projectDAO.getEmployeeProjects(employeeID);. If they are a different object representing a project, say EmployeeProject, you would need to replace the method body with the following code:
List<Project> projects = projectDAO.getEmployeeProjects(employeeID);
ArrayList<EmployeeProjectDetail> projectDetails = new ArrayList<EmployeeProjectDetail>();
for (Project project : projects) {
if(project.getProjectID == projectID){
projectDetails.add(project.getProjectDetail());
}
}