spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories

How can I print the name of an object in an ArrayList?


Looks like you want to print the name of the variable which meets certain criteria and is stored in your collection (your List). This is not possible in Java since at runtime you can't access to the name of the variables. In this cases, you should add a field in the class that helps you identify the object instance you're working with. This field could be an int id or String name (to keep it simple).

To make things easier, add this field in your Box class:

public class Box {
    //fields already declared here...
    //adding name field
    protected String name;
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Then, fulfill this field when creating the objects:

//setting the name of the object just
with the name of the variable
//just for understanding purposes
//you cannot access to the name of the variable at
runtime, no matter what
//also, you need to change the constructor of each
class accordingly
ShoeBox nike = new ShoeBox("nike");
Box present = new CandyBox("present",3,2,6);
JewelryBox gift = new JewelryBox("gift");
Box pictures = new ShoeBox("pictures");
Box skittles=new CandyBox("skittles",6,3,1);
CandyBox dots=new CandyBox("dots",3,2,1);
Box jareds=new JewelryBox("jareds");

And then, when an object matches with your criteria, you can use it for what you want/need e.g.

  • Criteria: The largest volume
  • What to do: display it's name to the user

Code:

double temp = 0;
Box boxWithLargestVolume = null;
for (Box box : boxes) {
    if (temp < x.getVolume()) {
        temp = x.getVolume();
        boxWithLargestVolume = box;
    }
}
if (boxWithLargestVolume != null) {
    System.out.println("The box with the largest
volume is: "
        + boxWithLargestVolume.getName());
}

Categories : Java

Related to : How can I print the name of an object in an ArrayList?
ConcurrentModificationException in ArrayList
Use a ListIterator, which allows you to make changes to the list through which you are iterating. The code you use is almost indentical in use to an iterator, but removing elements has to be done explicitly using the remove() method of the iterator. e.g. Iterator itr = tasked.iterator(); while(itr.hasNext()) { Villager e = itr.next(); if(!e.hasTask()) { itr.r

Categories : Java
How to add object to existing ArrayList? (java)
You method requires a Lamp argument, thus you should provide a Lamp object. Depending on how your Lamp method looks like, your main code should do something like: public static void main (String[] args) { Lamps ls = new Lamps(); ls.addLamp(new Lamp());//or provide additional arguments, if required. }

Categories : Java
Randomly inspecting an object in an arraylist
Instead of picking random elements, shuffle the array once and then iterate over the result: Collections.shuffle(objects); for (Object o : objects) { // you are now accessing objects in random order }

Categories : Java
ArrayList vs HashMap — Lots of Iterating and Object Manipulation
This answer addresses your concurrency concerns: A lot of iteration and object manipulation will need to be performed constantly (each main loop iteration can result in every single object in the data structure being modified in worst case, nothing modified in best/normal case). Will the collection be modified? If not just choose which ever collection makes most sense and synchronize on the

Categories : Java
how to get object into jsp from arraylist which is added into modelAndView inside controller
The term in ${...} is in jsp Expression Language and not java. Members of a List can be accessed like members of an array and bean properties by their name. Hence you should try: ${results[0].parameterName}

Categories : Java
Recently Add
Redirecting the output directory of 'mvn package' or 'mvn compile' command
No suitable constructor found for ProductoExtranjero
java Composite design pattern(Directory &File)
Java JTree's ui refresh after removing node from parent
First REST Spring application
How to cancel Indexing of a Solr document using Update Request Processor
PowerMock - Mock a Singleton with a Private Constructor
Calling a Postgres stored function SQL error
Where to store Morphlines Java custom command class?
Generic repository using map
How can I scroll a ScrolledComposited in Eclipse SWT Design view?
2 Frames/layout in 1 Activity
Writing a switch differently
Next button opens another activity when its reaches the array limit
Is EclipseLink MOXy capable of applying JSR-303 Bean Validation when unmarshalling XML to object?
Why my jdk can't work,and before the java_home, there is a space that is not from me
How to add List of objects in a Map
How to make notepad++ function like regular notepad in cmd?
Cell renderer and the lost focus
how can I implement iterable for LinkedList>
Disable Androids image-crunch in eclipse (run as) builds
java 8 lambda myMap.stream().count() != myMap.size() after merging myMap
Issue with Calendar calculation that spans 2 calendar years
JSF 2.0 Spring bean injection
Java Regex ReplaceAll with grouping
Getting any word and last word using sed
Clicking on link on JEditorPane throws IOException
printing out difference of two arrays
Spring Bean Alias in JavaConfig
Using Factory Method to Create Generics
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.