What is wrong with my constructor in java? - java

Is there a better way (probably..) to build a class in which i can use set/get method.
Notice thay all the data are stock in a ArrayList.
public class PorterList
{
public PorterList()
{
ArrayList<Porter> porList = new ArrayList<>();
}
public PorterList(ArrayList<Porter> p)
{
ArrayList<Porter> porList = p;
}
SimpleDateFormat porterDF = new SimpleDateFormat("HH:mm:ss");
private Porter p = new Porter();
private int _porterNo;
public String getStatus(int porterNo)
{
_porterNo = porterNo;
p = porList.get(_porterNo);
return p.p_state;
}
There's something wrong on that second last line p = porList.get(_porterNo);
I want to use something like this in my main:
p_L = PorterList(p)
porter_status = p_L.get(5)
Thank you very much

Yor ArrayList is local variable and it's your problem. It's should be a field.
private ArrayList<Porter> porList;
public PorterList() {
porList = new ArrayList<>();
}
public PorterList(ArrayList<Porter> p
{
porList = p;
}

As you declare ArrayList porList = p; inside the constructors , It will become local variable , so it will not be visible outside that constructor , If you want it to use at your class level declare it at globally liek below
public class PorterList
{
private ArrayList<Porter> porList;
public PorterList()
{
porList = new ArrayList<>();
}
public PorterList(ArrayList<Porter> p)
{
porList = p;
}
}

In both of your constructors you have declared local variable porList - make this a field
public class PorterList
{
private ArrayList<Porter> porList;
public PorterList()
{
porList = new ArrayList<>();
}
public PorterList(ArrayList<Porter> p)
{
porList = p;
}
....
}

Related

Object not recognized outside of constructor

I'm trying to create some methods for my object but the outside of the constructor, the object isn't recognized by it's name
public class Playlist extends SongRecord {
final int maxSongs = 50;
public Playlist() {
SongRecord[] list = new SongRecord[maxSongs];
}
public int size(){
return list.length();
}
}
The error message says list isn't recognized
Because your list scope is in the constructor if u want to access list every where u need to move your list to class scope
public class Playlist extends SongRecord {
final int maxSongs = 50;
SongRecord[] list;
public Playlist() {
list = new SongRecord[maxSongs];
}
public int size(){
return list.length();
}
}
Just move list to class scope:
public class Playlist extends SongRecord {
final int maxSongs = 50;
private SongRecord[] list;
public Playlist() {
list = new SongRecord[maxSongs];
}
public int size(){
return list.length();
}
}

Null Pointer Exception upon referencing variable

I am attempting to reference a variable in a method in my class and keep running into a NullPointerException. I know it is happening at the variable pbook when it is referenced from the addPerson method. Why is this happening and how could I go about fixing it?
public class Phonebook <T> {
private LinkedList<T> pbook;
public T findPerson(T person) {
for (int i = 0; i < pbook.size(); i++) {
if (pbook.get(i).equals(person)) {
return person;
}
else
{
i++;
}
}
return null;
}
public void addPerson(T person) {
pbook.addFirst(person);
}
public void deletePerson(T person) {
for (int i = 0; i < pbook.size(); i++) {
if (pbook.get(i).equals(person)) {
pbook.remove(i);
}
else
{
i++;
}
}
}
/**
* #param args
*/
public static void main(String[] args){
try{
Phonebook<Integer> sspb = new Phonebook<Integer>();
Phonebook<String> idpb = new Phonebook<String>();
sspb.addPerson(1234567890);
idpb.addPerson("Bob");
}
catch (Exception e){
e.printStackTrace();
}
}
}
You must add a constructor to instantiate your LinkedList:
public Phonebook() {
pbook = new LinkedList<T>();
}
Change:
private LinkedList<T> pbook;
To:
private LinkedList<T> pbook = new LinkedList<T>();
private LinkedList<T> pbook; You don't create a list.
Try this.
private LinkedList<T> pbook = new LinkedList<T>()
1) You can define a constructor e.g. like this.
public Phonebook(LinkedList<T> pbook){
this.pbook = pbook;
}
Then the calling code will have to set the
pbook when instantiating the Phonebook.
2) You can initialize pbook where you declare it.
private LinkedList<T> pbook = new LinkedList<T>();

how do I copy an object containing collections as fields

consider the below code:
public class Bid {
private double pe;
private List<ResChar> resourceList;
protected Map<Integer,Integer>scheduleOfSeller ;
public Map<Integer, Integer> getScheduleOfSeller() {
return scheduleOfSeller;
}
public void setScheduleOfSeller(Map<Integer, Integer> scheduleOfSeller) {
this.scheduleOfSeller = scheduleOfSeller;
}
private int bidId;
public int getBidId() {
return bidId;
}
public void setBidId(int bidId) {
this.bidId = bidId;
}
public double getPe() {
return pe;
}
public void setPe(double pe) {
this.pe = pe;
}
public List<ResChar> getResourceList() {
return resourceList;
}
public void setResourceList(List<ResChar> resourceList) {
this.resourceList = resourceList;
}
public Bid(int bidId,double pe, List<ResChar> resourceList){
setBidId(bidId);
setPe(pe);
setResourceList(resourceList);
this.scheduleOfSeller = new HashMap<Integer,Integer>();
}
}
I want to make a copy constructor of the bid like this :
public class BidCopy{
public Bid bid;
public BidCopy(Bid bidBuyer){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bidBuyer.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.bid = bidBuyer;
this.bid.setResourceList(resList);
}
}
The only solution that I know to make such copy is to proceed like follows :
public class BidCopy{
public Bid copy;
public BidCopy(Bid bid){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bid.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.copy = new Bid(bid.getBidId(), bid.getPe(), resList);
}
}
So I want to know if there is any other solution to make a copy of "Bid" Object more effectively ?
I would suggest making a copy constructor for your Bid object (and not a specific class for copying), a Bid is made out of its fields and not methods, like so:
public class Bid {
int ID;
String description;
Object bidStuff;
// ...as before
public Bid(Bid bid) {
this.ID = bid.ID;
this.description = bid.description;
this.bidStuff = bid.bidStuff;
}
public static void main(String[] args) {
List<Bid> original = new ArrayList<>();
// ..populate it
List<Bid> copy = new ArrayList<>(original.size());
for (Bid b : original) {
copy.add(new Bid(b));
}
}
}
You can even make the copy constructor protected or package-protected if you don't want anyone else to mess around with making multiple copies of bids.
There is not. Even though some collections have "copy constructors", these constructors will copy the elements' references, they will not create new elements for you.
You can however "optimize" the list creation itself by submitting the size of the initial list to the constructor:
List<X> newList = new LinkedList<X>(oldList.size());

Null pointer exception on getter setter in java

I have a getter setter class named SharedData.java . I am getting null pointer exception when I'm going to imply it on my code . Here is the SharedData class :
public class SharedData {
private static SharedData instance = null;
public SharedData() {
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}
public static void setInstance(SharedData instance) {
SharedData.instance = instance;
}
public double getSrc_latitude() {
return src_latitude;
}
public void setSrc_latitude(double src_latitude) {
this.src_latitude = src_latitude;
}
public double getSrc_longitude() {
return src_longitude;
}
public void setSrc_longitude(double src_longitude) {
this.src_longitude = src_longitude;
}
public double getEnd_latitude() {
return end_latitude;
}
public void setEnd_latitude(double end_latitude) {
this.end_latitude = end_latitude;
}
public double getEnd_longitude() {
return end_longitude;
}
public void setEnd_longitude(double end_longitude) {
this.end_longitude = end_longitude;
}
}
Here is my code :
SharedData sharedData ;
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);
Can anybody please help me with this ? Thanks .
You never initialized sharedData, so its value is null, calling a method on it got your program to crash.
I think you're trying to use Singleton Pattern. Try the below:
private static SharedData instance = new SharedData(); \\ Initialize here
private SharedData() { // Make it private....
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}
SharedData.getInstance();
Returns null. Later you're trying to call a method on it:
sharedData.setSrc_latitude(latitude);
Which is illegal as reference to object is still null.
You don't instanciate the class, so getInstance() returns null.
At the start of your class, replace :
private static SharedData instance = null;
by :
private static SharedData instance = new SharedData() ; // creates a new instance
change private static SharedData instance = null;
to private static SharedData instance = this;
and make your class static
public static class SharedData {
Also , make the getters setters static..
Even using the singleton pattern you should instantiate the object SharedData at least once.
try this
SharedData sharedData = new SharedData();
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);

NullPointerException.. Where is the flaw in my logic?

In Main:
Equipe Eq1 = new Equipe(J,E);
Equipe Eq2 = new Equipe(J,E);
while(Eq1.equals(Eq2))
Eq2 = new Equipe(J,E);
Match m = new Match(Eq1,Eq2);
String ChercherJoueur = m.QuelEquipe(m.hasBall());
In Class Equipe:
public Vector<Joueur> VJ;
public Equipe(Vector<Joueur> E, Vector<Entraineur> Ent) {
VJ = new Vector<Joueur>();
//rest of the logic
}
public Equipe() {
}
In Class Match:
Equipe Eq1 = new Equipe();
Equipe Eq2 = new Equipe();
public Match(Equipe Eq1, Equipe Eq2) {
Eq1 = this.Eq1;
Eq2 = this.Eq2;
}
public String QuelEquipe(Joueur J)
{
boolean found = Eq1.ChercherJoueur(J);
if(found == true)
return "EQ1";
else
return "EQ2";
}
public Joueur hasBall()
{
Joueur J = null;
int i = 0;
boolean found = false;
NullPointerException-------> System.out.println(Eq1.VJ.get(i).isBall());
System.out.println(Eq2.VJ.get(i).isBall());
while(!found)
{
if((Eq1.VJ.get(i).isBall())==true)
{
found = true;
J= Eq1.VJ.get(i);
}
else if((Eq2.VJ.get(i).isBall())==true)
{
found = true;
J= Eq2.VJ.get(i);
}
i++;
}
return J;
}
}
I think is all I need to include here to inform u about the situation.. I get a NullPointerException when I do "m.QuelEquipe(m.hasBall());" that can be traced back to where I pointed in The Class Match.. I know exactly what the exception means, and I'm changing their references with "Eq1 = this.Eq1;Eq2 = this.Eq2;" anyway.. sooo where is flow to get the code to work??
Your constructor using two args does initialize the vector but the parameterless constructor doesn't
public Equipe(Vector<Joueur> E, Vector<Entraineur> Ent) {
VJ = new Vector<Joueur>(); //<-- OK
//rest of the logic
}
public Equipe() {
//<-- errrk
}
Then when you invoke:
System.out.println(Eq2.VJ.get(i).isBall());
You're using really invoking:
Eq2.null.get <-- NullPointerException
But the real problem though is in the Match constructor:
public Match(Equipe Eq1, Equipe Eq2) {
Eq1 = this.Eq1;
Eq2 = this.Eq2;
}
Here you're assigning to the local variable Eq1 the value of the instance variable Eq1 you really want it the other way around:
public Match(Equipe Eq1, Equipe Eq2) {
this.Eq1 = Eq1;
this.Eq2 = Eq2;
}
BTW, this is not C# and in Java as a coding conventions both, methods and attributes start with lowecase and opening brace goes in the same line ( although this last part is not as relevant as the naming convention )
I hope this helps.
You are calling the default constructor public Equipe() which does not initialize VJ. Just remove the constructor if you are not going to use it.
This will fix your problem:
Match.java
private final Equipe eq1;
private final Equipe eq2;
public Match(final Equipe eq1, final Equipe eq2)
{
this.eq1 = eq1;
this.eq2 = eq2;
}

Categories