Creating multiple objects using the same instance - java

I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
private String style;
public Fighter() {}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
FightersDAO.java
public class FightersDAO {
public List<Fighter> getFighters(){
List <Fighter> fighter = new ArrayList<>();
String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };
for(int i=0; i < styles.length; i++) {
Fighter temp = new Fighter();;
temp.setStyle(styles[i]);
fighter.add(temp);
}
return fighter;
}
}
Demo.java
public class Demo {
private static FightersDAO fighterDAO;
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle()); //this should output the objects, but nothing shows
}
}
}
Why is it null? What part did went wrong

The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();
To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();

private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();

In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
List fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle());
}
}
}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();

Related

How to set & fetch fields of inner class in another class

package com.pr.trio;
import java.util.List;
public class lalala {
private List<SegmentationFieldValue> segmentationFieldValues;
public static class SegmentationFieldValue {
private Integer segmentationFieldId;
private Integer segmentationFieldGroupId;
private String value;
public Integer getSegmentationFieldId() {
return segmentationFieldId;
}
public void setSegmentationFieldId(Integer segmentationFieldId) {
this.segmentationFieldId = segmentationFieldId;
}
public Integer getSegmentationFieldGroupId() {
return segmentationFieldGroupId;
}
public void setSegmentationFieldGroupId(Integer segmentationFieldGroupId) {
this.segmentationFieldGroupId = segmentationFieldGroupId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public List<SegmentationFieldValue> getSegmentationFieldValues() {
return segmentationFieldValues;
}
public void setSegmentationFieldValues(List<SegmentationFieldValue> segmentationFieldValues) {
this.segmentationFieldValues = segmentationFieldValues;
}
}
package com.pr.trio;
import java.util.Arrays;
public class kk {
public static void main(String[] args) {
lalala l1 = new lalala();
//currently passed as an empty array, want to set SegmentationFieldId & value here from inner class
l1.setSegmentationFieldValues(Arrays.asList());
//lalala.SegmentationFieldValue.this.setSegmentationFieldId(15);
System.out.println(l1.getSegmentationFieldValues());
}
}
So here, I'm not able to pass values for the segmentation field instead of the empty array, gives an error. So how can I set the values from the inner class fields & pass it to my list?
Seeing as your SegmentationFieldValue class is public, it's trivial to use it inside another class, there are basically two ways to go about this:
The first is to import the inner class:
import com.pr.trio.lalala.SegmentationFieldValue;
The second is to qualify the classname whenever you use it:
lalala.SegmentationFieldValue a = new lalala.SegmentationFieldValue();
You can then call the setters on this class, and use the objects in your call to setSegmentationFieldValues:
lalala.SegmentationFieldValue a = new lalala.SegmentationFieldValue();
a.setSegmentationFieldId(1);
a.setSegmentationFieldGroupId(1);
a.setValue("a");
lalala.SegmentationFieldValue b = new lalala.SegmentationFieldValue();
b.setSegmentationFieldId(2);
b.setSegmentationFieldGroupId(1);
b.setValue("b");
l1.setSegmentationFieldValues(Arrays.asList(a, b));
Judging from your comment code, you also seem to be looking for a shorthand way to add an element to your list. A simple implementation could look like this (in class lalala):
public void addSegmentationFieldValue(Integer id, Integer groupId, String value)
{
if (segmentationFieldValues == null)
{
segmentationFieldValues = new ArrayList<>();
}
SegmentationFieldValue result = new SegmentationFieldValue();
result.setSegmentationFieldId(id);
result.setSegmentationFieldGroupId(groupId);
result.setValue(value);
segmentationFieldValues.add(result);
}
After which you can do the following in the main method of k1:
l1.addSegmentationFieldValue(1, 1, "a");

Convert array to string using an object from a different class

Hello I'm very new to Java and currently I'm trying to convert an array, that is a playfield, into a string through using a method(object) I created in a different class . This is what I have tried:
public class Testing
{
public static void main(String[] args) {
//create an empty playfield that is 10x10
Board emptyBoard = new Board(10,10);
//convert playfield to string and save it in new variable
String newBoard = convertToString(emptyBoard); // this throws an error saying "cannot resolve method 'convertToString(...)'
//now show the playfield as a string
System.out.println(newBoard);
}
}
The method convertToString lies in another class called ArrayToString, if that matters for any reason and "convertToString" should take in a Board and return a String. Any ideas on how to solve this kind of problem? :)
package foo;
// add static import to not write it before method name
import static foo.ArrayToString;
public class Testing {
public static void main(String[] args) {
// method should be static, because you don't use new ArrayToString().convertToString(emptyBoard)
String newBoard = convertToString(emptyBoard);
}
}
package foo;
public class ArrayToString {
// should be static method
public static String convertToString(Board board) {}
}

Java array list returning 0 value

I have created a class like this, which contains a bunch of arraylist as you can see. I've been setting the array with the methods add.. and then retrieving it with get.., when i tried to System.out.println numberofcitizen for example it is returning 0. Note that i have instantiated the class in another class to set the values.
public int numberOfCitizen;
private final ArrayList<Integer> citizenid = new ArrayList<>();
private final ArrayList<String> citizenName = new ArrayList<>();
private final ArrayList<Integer> citizenWaste = new ArrayList<>();
private final ArrayList<Float> longitude = new ArrayList<>();
private final ArrayList<Float> latitude = new ArrayList<>();
private final ArrayList<String> address = new ArrayList<>();
public void working() {
System.out.println("executing fine");
}
public void setnoOfcit(int number) {
this.numberOfCitizen = number;
}
public int getnumber() {
return this.numberOfCitizen;
}
public void addCitizenId(int citizen) {
citizenid.add(citizen);
}
public int getCitizenid(int i) {
int citId = citizenid.get(i);
return citId;
}
public void addCitizenName(String citizenname) {
citizenName.add(citizenname);
}
public String getCitizenName(int i) {
return citizenName.get(i);
}
public void addCitizenWaste(int waste) {
citizenWaste.add(waste);
}
public int getCitizenWaste(int i) {
return citizenWaste.get(i);
}
public void addLatitude(float lat) {
latitude.add(lat);
}
public float getLat(int i) {
return latitude.get(i);
}
public void addlng(float lng) {
longitude.add(lng);
}
public float getlng(int i) {
return longitude.get(i);
}
com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder vrpBuilder = com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder.newInstance();
public void runVPRSolver() {
System.out.println(numberOfCitizen);
System.out.println(getCitizenName(0));
//create a loop to fill parameters
Probable source of problem :
numberOfCitizen is a member attribute that you seem to never change. If you want it to represent the number of elements in your lists, either use citizenName.size() or increment the value of numberOfCitizen in one of the add methods.
Design flaw :
Your design takes for granted that your other class always use that one properly. Anytime you or someone uses that class, he must make sure that he add every single element manually. This adds code that could be grouped inside your class, which would be cleaner and easier to maintain.
So instead of several add method like this :
addCitizenid();
addCitizenName();
addCitizenWaste();
addLongitude();
addLatitude();
addAddress();
Design an other Citizen class which will contain those elements, and use a single list of instances of that class. That way you can use only one method :
private List<Citizen> citizenList = new ArrayList<>();
public void addCitizen(Citizen c) {
/*Add element in your list*/
citizenList.add(c);
}
This programming methodology is called "Encapsulation" which you can read about here
You need to increment numberOfCitizen in your add methods. For example:
public void addCitizenId(int citizen){
citizenid.add(citizen);
numberOfCitizen++;
}
I would also suggest encapsulating your variables into Objects, so create a citizen class:
public class Citizen {
private Integer id;
private Integer name;
private Integer waste;
}
And change your variable to an ArrayList of objects:
ArrayList<Citizen> citizens;

arraylist java compiling errors

ok i try to play with arraylist in java awhile to experiment some thing that related my project..so i come up with a simple code like this
having 3 file...DataStruc.java , DataStrucHand.java , testcase1.java
DataStruc.java
public class DataStruc {
private String testString;
public DataStruc(String s){
this.testString = s;
}
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
public String toString(){
return String.format("%s",testString);
}
}
DataStrucHand.java
import java.util.ArrayList;
public class DataStrucHand {
private ArrayList<DataStruc> ds;
public void addData(String ss){
ds.add(new DataStruc(ss));
}
public ArrayList<DataStruc> getData(){
return ds;
}
}
testcase1.java
import java.util.*;
public class testcase1 {
public static void main(String args []){
DataStrucHand dsh = new DataStrucHand();
String gdata = "test";
dsh.addData(gdata);
}
}
i tried to compile it and having this error
Exception in thread "main" java.lang.NullPointerException
at DataStrucHand.addData(DataStrucHand.java:7)
at testcase1.main(testcase1.java:8)
can i know what is wrong actually? i cant even add the data...i am trying to add the data and retrieve it back by creating another testcase2.java...but than i having problems in adding now to the arraylist...my purpose is to create a temp storage to keep a specific string that can be obtain by 1 program but runs with 2 different classes..
You never assign anything to the ds field.
DataStrucHand.java
import java.util.ArrayList;
public class DataStrucHand {
private ArrayList<DataStruc> ds; //I am null because nothing is ever new'd up here...
public void addData(String ss){
ds.add(new DataStruc(ss));
}
public ArrayList<DataStruc> getData(){
return ds;
}
}
Try it with this line:
private ArrayList<DataStruc> ds = new ArrayList<DataStruc>();
Or, you can have a constructor that will new it up if you prefer that method:
public DataStrucHand() {
ds = new ArrayList<DataStruc>();
}
You need to put an ArrayList<DataStruc> instance in ds.
You haven't instantiated the ArrayList. Write this:
public class DataStrucHand {
private ArrayList<DataStruc> ds = new ArrayList<DataStruc>();
public void addData(String ss){
ds.add(new DataStruc(ss));
}
You've never initialized ds, so it is null when you call ds.add(new DataStruc(ss)); Add a constructor to DataStrucHand that initializes ds, such as ds = new ArrayList<DataStruc>();.
The problem is that your DataStrucHand class never initializes its private field ds, so when you try to call ds.add(...) it fails with NullPointerException.
In fact, the way the class looks right now, there is no way ds can be anything else than null.
Shortest way to fix this is to initialize ds properly:
private final List<DataStruc> ds = new ArrayList<DataStruc>();
This way each DataStrucHand instance is constructed with an ArrayList inside and ds is never null.

Reflectively accessing a static variable in a Java class

I've been given no other choice but to access a set of classes, which I cannot modify, with this structure through reflection.
Using the method shown in the main method below however, throws a NullPointerException. The null pointer being "table" in the constructor when f1.get(null) is called.
I am unable to instantiate the classes beforehand because the only constructor is the one shown, which is private. So there is no way for me to explicitly set table either.
Anyone know of a way for me to reflectively call Legacy.A?
public class Legacy {
public static final Legacy A = new Legacy("A");
public static final Legacy B = new Legacy("B");
private String type0;
private static Map<String, Legacy> table = new HashMap<String, Legacy>();
private Legacy(String id) {
type0 = id;
table.put(type0, this);
}
public static void main(String[] args) throws Exception {
Field f1 = Legacy.class.getDeclaredField("A");
Object o = f1.get(null);
}
}
In before "Reflection == BAD!!!"
The order of the static initializers is wrong, table must come before the constructor calls.
This is the reason that you get the exception when the class is loaded and initialized. This has nothing to do with reflection.
Since this is confusing, I would write it like this:
public class Legacy {
static {
table = new HashMap<String, Legacy>();
A = new Legacy("A");
B = new Legacy("B");
}
public static final Legacy A;
public static final Legacy B;
private String type0;
private static Map<String, Legacy> table;
private Legacy(String id) {
type0 = id;
table.put(type0, this);
}
public static void main(String[] args) throws Exception {
Field f1 = Legacy.class.getDeclaredField("A");
Object o = f1.get(null);
}
}
This way, even if the members change location (due to refactoring, line alignment or whatever) the code will always work.
I tried this, because I couldn't see what was wrong with your example. It worked if I reordered the declarations:
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class Legacy {
private String type0;
private static Map< String, Legacy > table = new HashMap< String, Legacy >();
private Legacy( String id ) {
type0 = id;
table.put( type0, this );
}
public static final Legacy A = new Legacy( "A" );
public static final Legacy B = new Legacy( "B" );
public static void main( String[] args ) throws Exception {
Field f1 = Legacy.class.getDeclaredField( "A" );
Object o = f1.get( null );
}
}
The static declarations need the (preceding) constructor.

Categories

Resources