fetching data from ArrayList [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have method which returns List of objects, I m facing a problem while fetching a data from list, I m getting null pointer exception when i am trying to fetch the data.
method which returns List:
public List <EstimationResivion> getEstimationRevision(double rev_id){
List<EstimationDetailRevision> estDetail=estDetailRev(rev_id);
List<EstimationPanelRev> estPanelrev=estPanelRev(rev_id);
List<EstimationPannelDetailRevision> estimationpaneldetailrev=estPanelDetailRev(rev_id);
List<EstimationResivion> estRev=estRevision(rev_id);
EstimationResivion ed= new EstimationResivion();
ed.setEstimationdetailRev(estDetail);
ed.setEstimationpanelRev(estPanelrev);
ed.setEstimationpaneldetailRev(estimationpaneldetailrev);
System.out.println("Size before: "+estRev.size());
estRev.add(ed);
return estRev;
}
estDetailRev code:
private List<EstimationDetailRevision> estDetailRev(double d){
return getJdbcTemplate().query("SELECT * FROM estimation_detail_rev WHERE rev_id=?", new Object[] {d }, new EstimationDetailRevRowMapper());
}
estRevision code
private List<EstimationResivion> estRevision(double d){
return getJdbcTemplate().query("SELECT * FROM estimation WHERE est_revision=?", new Object[] {d }, new EstimationRevRowMapper());
}
estRevision will return list of List<EstimationResivion> which i am storing in estRev.
code from where i am calling getEstimationRevision and trying to fetch data from list
public void getRevision(){
double d=0;
List<EstimationResivion> est=estimationdao.getEstimationRevision(d);
for(EstimationResivion er:est){
System.out.println(er.getEstContactPerson());
System.out.println(er.getEstCustomer());
System.out.println(er.getRevId());
// epd=er.getEstimationpaneldetailRev();
List<EstimationDetailRevision> edr=er.getEstimationdetailRev();
for(EstimationDetailRevision estimaitonDetail:edr){
estimaitonDetail.getCompCategory();
estimaitonDetail.getCompMake();
}
}
I am getting null value when i call er.getEstimationdetailRev();
if i specify the index i am able to getdata something like this:
List<EstimationDetailRevision> edr=est.get(64).getEstimationdetailRev();
My question is how can i fetch data without specifying index ?

One of your elements is null (not a value). Let's find out which,
// for(EstimationResivion er:est){
for (int index = 0; index < est.size(); index++) {
EstimationResivion er = est.get(index);
if (er == null) {
System.out.println("element at index " + index + " is null");
continue; // <-- move to the next index
}
// ...
List<EstimationDetailRevision> edr=er.getEstimationdetailRev();
if (edr == null) {
System.out.println("edr at index " + index + " is null");
continue; // <-- move to the next index
}
Also, you could (and should) use a debugger on your code.

Related

Removing a selected object from an array [duplicate]

This question already has answers here:
Remove specific index from array in java
(6 answers)
Why we need to override hashCode and equals?
(4 answers)
Closed 5 years ago.
I have created an array of objects (object representing a flight),
and i'm trying to create a method to remove a specific object from that array, without changing it's length.
I have written the following method :
public boolean removeFlight (Flight f) {
for (int i = 0 ; i < _noOfFlights ; i++) {
if (_flightsSchedule[i].equals(f)) {
_flightsSchedule[i] = _flightsSchedule[(i+1)];
_noOfFlights--;
return true;
}
}
return false;
}
_noOfFlights represents the number of object currently in the array.
For some reason it returns "false" when given an object that was added to the array.
You need to be careful not to change the ground under your feet. You also don't want to return in the middle of the loop, otherwise you won't have moved all the elements properly.
You could do something like this:
public boolean removeFlight (Flight f) {
boolean found = false;
for (int i = 0 ; i < _flightsSchedule.length; i++) {
if (f.equals(_flightsSchedule[i])) {
found = true;
} else if (found) {
_flightsSchedule[i - 1] = _flightsSchedule[i];
}
}
if (found) {
_noOfFlights--;
_flightsSchedule[_flightsSchedule.length - 1] = null;
}
return found;
}
Also, note that I've set the last element to null to avoid an inadvertent memory leak.

How to fix ConcurrentModificationException when using foreach to iterate over a List? [duplicate]

This question already has answers here:
Java - adding elements to list while iterating over it
(5 answers)
Closed 5 years ago.
am trying to add objects to an arraylist after verifying either that object already exits in the list or not. But am getting a ConcurrentModificationException and I don't know how to fix it.
Any help?
here is the code that throws the exception:
List<ContexteNb> projets = service.findByprojet(p);
List<ProjetVTO> models = new ArrayList<>();
for (ContexteNb contexteNb : projets) {
ProjetVTO model = new ProjetVTO();
model.setNbillets(contexteNb.getNbBillet());
model.setAnnee(contexteNb.getDimDate().getAnnee());
model.setPriorite(contexteNb.getDimPriorite().getPriorite());
if (models.isEmpty()) {
models.add(model);
}
else{
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee())
&& (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
} else {
models.add(model);
}}}}
thanks,
The exception results from adding an element to the models List while iterating over it.
You have to change your logic. I suspect the logic of your inner loop is wrong anyway, and fixing it will also solve your problem. You probably want to search first if the List contains any element matching model and modify it if found, and only add a new instance to the List if you don't find a match (i.e. after the loop is over).
Your inner loop would look like this:
if (models.isEmpty()) {
models.add(model);
} else {
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}
}
or simply (you can eliminate the outer condition):
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}

Passing method of one class into another [duplicate]

This question already has answers here:
Passing a method from another class
(4 answers)
Closed 5 years ago.
My problem is that I need to getSymbol from Element class.
I would normally establish an object in PeriodicTable like this:
Element e = new Element();
then use e.getSymbol within method in order to use it for comparison.
So, in order to complete first task and print entire list of elements, I declared an array within PeriodicTable like this:
Element[] objects = new Element[ARRAY_SIZE];
I'm guessing I declared it correctly, as it does run entire list of elements.
Again, I am having problems getting getSymbol into my method in PeriodicTable.
Any helpful suggestions, please?
For this method, a user will input a symbol for an element. The method will search for the element and return its index (in the array). Then, it will use the index to display that single element and all of its other information, using the toString method from the Element class.
public int searchBySymbol(String sym)
{
int index = 0;
boolean found = false;
for (int i = 0; i < objects.length; i++)
{
objects[i] = objects.getSymbol;
}
while (index < objects.length && !found)
{
if (objects[index].equals(sym))
{
found = true;
}
else
{
index++;
}
}
if(found)
{
System.out.println("Found at position: " + index);
System.out.println(objects[index].toString());
}
else
{
System.out.println("Not found");
}
}
You definitely don't need two loops in there first of all, there are two solutions to this:
(Recommended) If searching Elements by symbol will be the your main way of looking up Elements, consider using a HashMap to contain the data rather than an Element array as HashMaps allow look up of objects by a key e.g. HashMap<String, Element>. Lookup the HashMap API or check this example: http://beginnersbook.com/2013/12/hashmap-in-java-with-example/
(Quick fix) Rather than using two loops to get the field and compare, in Java it is good practice to define accessor methods such as getSymbol() and return the field rather than directly accessing it. Using this method you can simplify your code into...
for (Element e : objects) {
if (e.getSymbol().equals(sym) {
return true;
}
}
//return false after the loop omits the need for an explicit boolean variable`
Edit: Usual for loop construct for index access. The index number is essentially tracked by the iterator variable int i so you do not need a separate variable to track it.
for (int i = 0; i < objects.length; i++) {
if (objects[i].getSymbol().equals(sym)) {
//print i to show index number
//print objects[i].toString();
return true;
}
}
//print not found...
return false;

null pointer exception while searching linked list [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I created a search method for a linked list. It works correctly when I search for something that does exist in the list. If I search for something not in the list, then I get a null pointer exception.
I don't see how its possible to get this exception.
Here is the method:
// these two search methods return the node containing the substring given
public UNode search(String cityName)
{
return search(cityName,this);//line 90
}//end search()-------------------------------------------------------------
private UNode search(String cityName, UNode current)
{
if(current != null)
{
if (current.getCity().getName().contains(cityName))
{
System.out.println("Node '" + current.getCity().getName()
+ "' has been found and returned.");
return current;
} else
{
return search(cityName,current.next);//line 105
}
}
else
{
System.out.println("No node containing the substring '"
+ cityName + "' can be found, returning null");
return null;
}
}//end search()-------------------------------------------------------------
To my understanding, this is what happens when searching for something that does not exist: The method keeps calling search() recursively with current.next, it gets to the last element and calls search(cityName, null), then since current is null, it says it is not found, and returns null.
Am I missing something here? What am I doing wrong? Should I just throw the null pointer exception?
Here is the method where I call the search method:
public static void uNodeTest(City[] cities)
{
UNode unvisited = new UNode();
unvisited.addCities(cities);
String a = unvisited.getNext().getNext().getNext().getCity().getName();
System.out.println(a);
UNode current = unvisited;
while(current.getNext() != null)
{
System.out.println(current.getCity().getName());
current = current.getNext();
}
UNode phil = unvisited.search("not a city");
}
Stack Trace:
java.lang.NullPointerException
at cityproject.UNode.search(UNode.java:105)
.
.
.
at cityproject.UNode.search(UNode.java:105)//(omitting repeats)
at cityproject.UNode.search(UNode.java:90)
at cityproject.CityProject.uNodeTest(CityProject.java:104)
at cityproject.CityProject.main(CityProject.java:79)
I would add a check before calling the recursive search to see if current.next is null:
if(current.next != null) {
return search(cityName,current.next);
}
else {
return null;
}
This might solve the null pointer exception...

Check if ResultSet is empty in Java [duplicate]

This question already has answers here:
Java ResultSet how to check if there are any results
(23 answers)
Closed 8 years ago.
I am using HSQLDB in my program. I want to check if my Result Set is empty or not.
//check if empty first
if(results.next() == false){
System.out.println("empty");
}
//display results
while (results.next()) {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
}
The above method is not working properly. According to this post I have to call .first() or .beforeFirst() to rest the cursor to the first row, but .first() and .beforFirst() are not supported in HSQL. I also tried to add connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
but I still get the same outcome (I get the message empty and the data from the DB!!!)
What am I doing wrong here?
If I understand your objective, you could use do while loop
if (!results.next()) {
System.out.println("empty");
} else {
//display results
do {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
} while (results.next());
}
Or, you could just keep a count like so,
int count = 0;
//display results
while (results.next()) {
String data = results.getString("first_name");
//name.setText(data);
System.out.println(data);
count++;
}
if (count < 1) {
// Didn't even read one row
}

Categories