Accessing Objects from ArrayLists - java

I have an arraylist of objects that I am sending from class "Testing" to class "Subjects", but can't access some of the methods in the Subjects class.
I would like to be able to simply send an arraylist of "Subject" objects (from the Testing class) to a method in the Subject class and be able to use other methods within the Subject class.
public class Subject {
private String subjectName;
private String courseCode;
//getters and setters for subjectName and courseCode
I can access the following method if I just call it from the Subject class, but not from the Testing class.
public String getDiscipline(){
int a = courseCode.length()-3;
String discipline = courseCode.substring(0, a);
return discipline;
}
In the method below, I can return and print objects and call the method I want, but only for one object...
public List<?> allDisciplines(ArrayList<?> inputSubjects){
for (int i = 0; i<inputSubjects.size(); i++){
System.out.println(inputSubjects.get(i)); //this returns all the
//objects, but why won't this work instead?: inputSubjects.get(i).getDiscipline();
}
//initialise new arraylist
List<String> dis = new ArrayList<>();
dis.add(getDiscipline()); //This works, but only for whatever single
//object I used to call the allDisciplines
//method with
//
return dis;
}
In another class , I pass the object array "subjects" into the allDisciplines method of the Subject class.
public class Testing {
public static void main(String[] args) {
// TODO code application logic here
Testing program = new Testing();
program.start();
}
public void start(){
//gets the data from a file, converts it into "Subject" objects with
//subjectName and courseCode
The following works because it's only sending one object through and I only get one result.
subjects.get(3).allDisciplines(subjects);
But if I try to access the allDisciplines method from the Testing class, I can't because it's not static and if I make the class static, it needs the private ints to be static which then don't change between iterations of my loops and I end up with the same value for fields.
allDisciplines(subjects); //does not work - can't see the allDisciplines
//method
I am not sure whether the problem is because I can't access the method outside of its class or because I am not properly referencing the objects in the arraylist.
Thanks for any help you can give me - I am quite confused!

I think the problem is the allDisciplines method. It should be static. You seem to not quite understand generics. I rewrote it for you:
public static List<String> allDisciplines(ArrayList<Subject> inputSubjects){
//initialise new arraylist
List<String> dis = new ArrayList<>();
for (Subject subject : inputSubjects) {
dis.add(subject.getDiscipline());
}
return dis;
}
I looped through the subjects passed in and added the discipline of each to a new array list and returned it. I also changed List<?> to List<Subject> because we are expecting the client code to pass a list of subjects.
Another shorter way to implement this:
public static List<String> allDisciplines(ArrayList<Subject> inputSubjects){
return inputSubjects.stream().map(Subject::getDiscipline).collect(Collectors.toList());
}
Now you can call allDisciplines by
Subject.allDisplines(subjects)
in Testing.

Related

Creating a class that has a linked list in the constructor

I've been asked to do something weird and I need to make a class that is a word set (for a spell checker) and I have to do it using a linked list.
What I've tried for the constructor is this:
public WordSet(LinkedList<String> list) {
LinkedList<String> wordSet = list;
}
But this doesn't let me reference the wordset in the rest of the class. BTW this class doesn't have a main or anything like that
its essentially just a data structure which wraps around a linked list (no I have no idea why they want me to do it).
Can someone tell me what I'm doing wrong here?
As an example of a method in this class, one is:
public void insertWord(String s){
}
where I have to add a word to the wordset, now I know that linked lists have this functionality already
in them but I don't know how to reference a linked list from a constructor because of course the linked list hasn't been instantiated, and can't be because this has no Main() method and I can't just go referencing it from the Class that does have a main method because that's messy.
Create a LinkedinList as a class atribute then try to initialitate it to the constructor so u can after use it when u create an object of the current class
public class WordSet {
private LinkedList<String> list;
public WordSet() {
list = new LinkedList<>();
}
public void insertWord(String s){
list.add(s);
}
What you can do is something like this. First create a class that will have reference variable of your list and then a method for inserting new words. When creating a new object, we want user to "provide" a list on which he/she will work later. Meaning each user will have different list - which is why our constructor has argument of type List.
public class Main {
List<String> words;
public Main(List<String> words) {
this.words = words;
}
public void insertWord(String s){
words.add(s);
}
}
You then create your own list and put that same list inside constructor. Once you have constructed an object, you can insert new words inside your list.
class Test{
public static void main(String[] args) {
List<String> myWords = new LinkedList<>();
myWords.add("table");
myWords.add("window");
myWords.add("car");
Main obj = new Main(myWords);
obj.insertWord("carpet");
//shows all your words
System.out.println(myWords);
}
}

How do you add to an ArrayList using generics?

I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.
import java.util.ArrayList;
public class Ballot {
private ArrayList<Candidate> ballot;
private String officeName;
public Ballot(String officeName) {
this.officeName = officeName;
ArrayList<Candidate> ballot = new ArrayList<Candidate>();
}
public String getOfficeName() {
return officeName;
}
public void addCandidate(Candidate c) {
ballot.add(c);
}
public ArrayList<Candidate> getCandidates() {
return ballot;
}
public static void main(String[] args) {
Ballot b = new Ballot("Election");
b.addCandidate(new Candidate("Sarah", "President"));
System.out.println(b);
}
}
When I try to run the document, it throws a NullPointerException. What am I doing wrong?
The constructor initializes a local variable named ballot that hides the data member with the same name. Then, when you try to add to it, it fails with a NullPointerException, since it was never initialized. If you initialize it you should be OK:
public Ballot(String officeName) {
this.officeName = officeName;
ballot = new ArrayList<Candidate>(); // Here!
}
You're not initializing your list of candidates properly in the Ballot constructor. You need to do:
this.ballot = new ArrayList<Candidate>();
Right now you're just creating a local variable named ballot in the constructor which shadows the actual class field. Since it has never been initialized, you end up getting a NullPointerException when you eventually try to add an element to it.
Also, as a best practice, use interfaces instead of the concrete type. This makes it easy to change implementations later. So instead of defining the field as private ArrayList<Candidate> ballot;, define it as private List<Candidate> ballot;.
As simple that you are not using this object. You are never initiliazing your object
Correct way
public Ballot(String officeName) {
this.officeName = officeName;
this.ballot = new ArrayList<Candidate>();
}
You're overriding your class variable with a local variable of the same name. Either initialize the list directly
private List<Candidate> ballot = new Arraylist<>();
or initialize it in the constructor with
ballot = new ArrayList<>();
FYI: You shouldn't assign implementation classes for your local variables and return values if you can help it. "ballot" should just be the List interface as should the getter. That way if you ever want to change the implementation, you don't have to change everything. It could be an ArrayList, LinkedList, Stack, Vector, etc and it won't matter because they're all using the List interface.

Can't reference two classes inside one?

I'm utilizing object oriented programming for the first time in Java and haven't had any issues until now.
I have a Customer class (irrelevant details omitted):
public class Customer {
public String bikesOwned;
public Customer() //Default Constructor
{
bikesOwned = "";
}
public Customer(String aBike) //Parameterized Constructor
{
addBike(aBike);
}
public void addBike (String aBike) //Mutator Method for Bikes Owned
{
bikesOwned = aBike;
}
public String toString()
{
String returnBikes = bikesOwned.toString();
return returnBikes;
}
}
And I have a Bike Tester class which uses information from my Bicycle class:
public class bikeTester {
public static void main (String [] args)
{
Bicycle hisBike = new Bicycle(Bicycle.BikeType.Hybrid Bicycle.UserType.Men,
Bicycle.FrameMaterial.Carbon, Bicycle.BrakeType.Caliper,
Bicycle.Condition.Used, 29, 18, 10, "REI", "Black");
Customer don = new Customer();
don.setFirstName("Don");
don.setLastName("Norman");
don.setPhoneNumber("804 123-4567");
don.setEmailAddress("dnorman#aol.com");
don.addBike(hisBike);
System.out.println(don);
System.out.println();
}
My issue is that when I compile, I get this error:
"addBike(java.lang.String) in Customer cannot be applied to (Bicycle)".
I can't figure out why everything else is working except for addBike. Any ideas? Any input is very appreciated.
Your addBike method expects a String parameter:
public void addBike (String aBike)
But you're sending it a Bicycle parameter:
don.addBike(hisBike);
Either send the method a String or change the method to accept a Bicycle (or add another method of the same name which accepts a Bicycle).
It's not entirely clear to me how you would convert between a String and a Bicycle, especially given that the method itself is just setting a value called bikesOwned which itself is a String for some reason. Maybe bikesOwned should be a list or collection of some kind and you want to add items to that collection?
The logic of what you ultimately want this code to do is up to you. But the error itself is pretty straightforward. String and Bicycle are two different things.
The addBike method receives a String parameter but you are sending a Bicycle type to the function. It's basically a type mismatch.
Try sending a Stringvalue to the function.
Or, change the parameter in the addBike method to Bicycle type.
You're trying to pass a "Bicycle" instance from
don.addBike(hisBike);
into a method:
public void addBike (String aBike)
that takes a string parameter.
Either change your method to accept a Bicycle instance (and presumably add it to some array of owned bikes) or if you meant to just pass in the name of the bike for instance, change the call accordingly.

How to create an object of List from another class in main method?

I have to create an Object of List in main Method but i have no idea how to do it. Constructor of class, that i want to create an Object has an List as a parameter.
How can i create an Object of CashMachine class?
By the way I am not going to write all of the classes, because it is long.
Here are my classes:
public class CashMachine {
private State state;
List<Account> accountList;
private CashCard cashCard;
private Account selectedAccount;
public CashMachine(List<Account> accountList){
this.accountList = accountList;
}
}
public class TestMain {
public static void main(String[] args) throws Exception {
CashMachine cashMachineObj = new CashMachine(); //it is false
}
}
You wrote a constructor, that wants a List ... so surprise, you have to provide one.
Simple, will compile, but is wrong:
CashMachine cashMachineObj = new CashMachine(null);
Better:
CashMachine cashMachineObj = new CashMachine(new ArrayList<>());
The above simply creates an empty list and passes that into the CashMashine.
In other words: there are many ways to create lists; and you can pick whatever approach you like. Even things like:
CashMachine cashMachineObj = new CashMachine(Arrays.asList(account1, account2));
where account1, account2 would be existing Objects of the Account class.
If you read the docs for List, you will see that List is actually an interface!
Interfaces are like protocols. The methods in interfaces don't have implementations. The classes that implement the interface must provide those implementations. You can't just create a new List object by calling its constructor because it doesn't make sense to create an object with methods that have no implementations!
What you should do is to create an object of a class that implements List, for example, ArrayList.
ArrayList<Account> accounts = new ArrayList<>();
You can now pass accounts to the constructor of CashMachine.

How to access non static cloned arrayList for use in static method in Java

As part of an assignment Im trying to access a cloned array list from another class so I can utilize it. But when attempting to do so I get the following error "non-static method getConnections() cannot be refrenced from a static context".
This is the code I'm using to access the cloned array. It is in the context of working out the best way to take flights from one destination to another.
public boolean determineRoute(City from, City to, ArrayList<City> flightRoute)
{
ArrayList<City> Connections = new ArrayList<City>();
Connections = City.getConnections();
return true;
}
And this is how the code for that class begins. It does start as static but as far as i can see it should only affect the first method how can I tell java that this method should not be considered static so I can access the cloned list from the non static class??
import java.util.*;
public class Lab9_Ex2_Main
{
//////// START-UP /////////
public static void main(String[] args)
{
new Lab9_Ex2_Main();
}
I have left out a lot of the code as I think it may not be right from me to put every thing up. But should you need more to get a clearer picture I will happily add more of the code.
This is the code from another class which contains a cloned array which im attempting to access.
import java.util.*;
// Class: City
// Purpose: To represent a place in the world that you can fly from/to.
public class City
{
private String name; // The name of the City
private ArrayList<City> connectsWith; // Which cities are connected to this one
public City(String cityName)
{
name = cityName;
connectsWith = new ArrayList<City>();
}
// Method: addConnection
// Purpose: To note that you can catch a flight to the destination, from this city
// Passed:
// destination - The City which you can fly to.
public void addConnection(City destination)
{
if (destination != null && destination != this)
connectsWith.add(destination);
}
// Method: getConnections
// Purpose: To retrieve a list of cities you can reach from this one.
// Note: You are given a clone, (to avoid a privacy leak), and can manipulate it however
// you like. E.g. you could delete elements.
public ArrayList<City> getConnections()
{
return (ArrayList<City>) connectsWith.clone();
}
public String getName()
{
return name;
}
public String toString()
{
return name;
}
}
City actually doesn't provide a static getConnections() method, since that doesn't make sense. The connections depend on an actual City instance and if you have access to one you can call getConnections() on it, even from a static method.
This is the comment on the array list that is cloned in getConnections():
// Which cities are connected to this one
Note that this means you just can't get the connections without specifying this city (the one you get the connections for) and thus just can't call that method on the City class only.
Comment on the method itself:
Purpose: To retrieve a list of cities you can reach from this one.
Assuming your determineRoute(...) method might be static, it could look like this:
public static boolean determineRoute(City from, City to, ArrayList<City> flightRoute)
{
ArrayList<City> connections = new ArrayList<City>();
connections = to.getConnections(); //or from.getConnections(); what ever makes sense
//connections is not used, so I assume you want to put them into flightRoute
flightRoute.addAll(connections);
return true;
}
Your determineRoute(...) logic seems quite odd. I assume you want to actually calculate the route between the from and the to city, which you are not doing right now. Fixing that, however, is an exercise for you.
You could then call that method in your main method (which has to be static) like this:
public static void main(String... args) {
City berlin = new City("Berlin");
City beijing = new City("Beijing");
//fill the connections here
ArrayList<City> route = new ArrayList<City>();
boolean success = determineRoute(berlin, beijing, route);
}

Categories

Resources