How to retrieve list values from overriden methods - java

I have an MVP setup where the presenter populates two RecyclerViews separately with the following methods:
#Override
public void populateFollowsRV(List<FollowsRVModel> userDataList) {
followsList.addAll(userDataList);
followsAdapter.notifyDataSetChanged();
}
#Override
public void populateFollowedByRV(List<FollowsRVModel> userDataList) {
followedByList.addAll(userDataList);
followedByAdapter.notifyDataSetChanged();
}
I have a separate third method in which I would like to retrieve the lists contents of followsList and followedByList, I have tried to declare a global variable called listOne in the Fragment class and then storing the contents of followsList/userDataList when populateFollowsRV() is called in order to have the contents accessible by other methods in the class but this doesn't seem to work:
//Declare listOne inside the Fragment class
private List<FollowsRVModel> listOne = new ArrayList<>();
#Override
public void populateFollowsRV(List<FollowsRVModel> userDataList) {
followsList.addAll(userDataList);
followsAdapter.notifyDataSetChanged();
//Assign the contents of userDataList to listOne when the presenter calls populateFollowsRV()
listOne = userDataList;
}
listOne still appears to be empty after this.
Third Method
public void populateNonFollowersRV() {
//To test wether listOne has any content
String.valueOf(listOne.size()));
}

Related

object values not the same after changes in an arraylists?

I'm having an issue with some pointers from what I can read about java. It always passes parameters as values rather than references. here
I have a project and employee class that should "share" an object but when I create an instance of activity, add it to the project list and then later add it to the employee list of activities it works. But then when I change the worktime for an employee it's only visible via the project instance where i add the worktime from. It's not visible when i then call the activity worktime from the employee object.
Is there a way to "share" an object between classes e.g. pass it by reference like you can in PHP?
When I output the hashcodes of the activity objects in both classes they are also different...
Project class:
public class Project {
private List<Activity> activites = new ArrayList<Activity>();
public List<Activity> getActivities() {
return activites;
}
public void setActivities(Activity activity) {
this.activites.add(activity);
}
}
employee class:
public class Employee {
private List<Activity> activities = new ArrayList<Activity>();
public List<Activity> getActivities() {
return activities;
}
public void setActivity(Activity activity) {
activities.add(activity);
}
}
activity class:
public class Activity {
private String activityName;
private HashMap<Employee,Integer> workTime = new HashMap<Employee,Integer>();
public Activity(String activity) {
this.activityName = activity;
}
public HashMap<Employee, Integer> getWorkTime() {
return workTime;
}
public void setWorkTime(Employee e, Integer t) {
workTime.put(e, t);
}
}
An example of the issue:
public void main(String[] args) {
Activity a = new Activity('task i');
Project p = new Project();
p.setActivities(a);
Employee e = new Employee();
e.setActivity(a);
p.getActivities().get(0).setWorkTime(e,5);
System.out.println(p.getActivities().get(0).getWorkTime()); // 5
System.out.println(e.getActivities().get(0).getWorkTime()); // -> null (would like 5)
}
The problem is here
public void setWorkTime(Employee e, Integer t) {
workTime.put(e, t);
}
You are putting the employee instance in a map. But the Employee class does not override equals and hashCode so every instance of Employee will be a new and unique key.
You need to override equals and hashCode using some field(s) of the Employee class that would constitute equal instances (e.g. Employee name and/or Employee ID).
UPDATE
In recognition of the comments regarding only a single instance of Employee is being used, I concur. Although I believe it is important to do as I suggested it was not the specific problem.
I ran the above code and made main a static entry point and fixed the Activity argument to correctly add a String. The OP originally had the following:
System.out.println(p.getActivities().get(0).getWorkTime()); // 5
System.out.println(e.getActivities().get(0).getWorkTime()); // -> null (would like 5)
The above does not print 5 or null. It prints the default toString of the map.
The Employee instance must must be supplied as the key via get and it will print 5 in both cases.
System.out.println(p.getActivities().get(0).getWorkTime().get(e)); // 5
System.out.println(e.getActivities().get(0).getWorkTime().get(e)); // 5

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);
}
}

Assigning ArrayList object to Instance variable - java

The code snippet below is part of some code I am reading for an assignment but I cant understand the role of the copy variable in the snippet or what it does. I know its an instance of the Sample class, but why it is then assigned an ArrayList is not clear to me.
public class Sample implements Var{
private List lst1;
private List lst2;
public Sample() {
super();
}
public Sample(List lst1) {
this();
this.lst1 = lst1;
}
public List getLst1() {
return lst1;
}
public void setLst1(List lst1) {
this.lst1 = lst1;
}
#Override
public Var copy(){
Sample copy = new Sample(lst1);
copy.lst2 = new ArrayList(lst2);
return copy;
}
#Override
public void randomize(){
}
}
In fact the error message is explicit to show that you can't iterate over the variable copy because you haven't implemented the Iterable interface which allows you to do it. If you insist to loop over it and to have functions allowing you to do so: just visit this link Java Generics - Implementing the Iterable Interface where you can for exemple (if this is what you want) iterate over the elements of the two lists of an instance lst1 and lst2

ArrayList.add() not adding, not returning errors

For my AP CompSci class, we're making a "Contacts" program to simulate using a virtual phonebook. The main class, Contacts is as follows.
public class Contacts extends ArrayList<Contact>
{
private ArrayList<Contact> contacts = new ArrayList<Contact>();
#Override
public boolean add(Contact c)
{
contacts.add(c);
Collections.sort(contacts);
return true;
}
public ArrayList<Contact> search(String name)
{
ArrayList<Contact> temp = new ArrayList<Contact>();
for(int i = 0; i<=contacts.size(); i++)
{
if(contacts.get(i).getName().equals(name))
{
temp.add(new Contact(name));
}
}
return temp;
}
}
As you can see, it extends ArrayList<Contact>. Contact is a simple object, composed of a String name and a 7-integer int num. The problem lies in the class ContactsFactory, where I loop through a text file to create a huge ArrayList of names.
public class ContactsFactory {
public static Contacts getContacts() throws FileNotFoundException {
String path = System.getProperty("user.dir");
Scanner s = new Scanner(new File(path + "\\src\\names.txt"));
Contacts contacts = new Contacts();
do {
contacts.add(new Contact(s.next()));
} while (s.hasNext());
s.close();
//print size to see anything added. It returns 0.
System.out.println(contacts.size());
return contacts;
}
}
However, when I implement the add() method for each name, not only does it seem not to add anything, but it returns no error. Even more interesting is that, as I found out when I put a print statement after every iteration, s.next() is no empty String. But the String(which experiences no issues being transferred from names.txt) is not added to contacts, and as a result, the ArrayList ends up empty with a size() of 0.
I think the error might be in the overridden Contacts.add() method, but I haven't been able to figure anything out. Can someone help me out? Thanks in advance.
I'm wondering why you extend ArrayList and additionally keep another copy of an ArrayList around. Besides the overwritten add (and size from azurefrog's answer), an ArrayList as well as the List interface offers a bunch of other methods - instead of overwriting all of them and delegating to the internal list, I would just rely on those methods and add the functionality I need:
public class Contacts extends ArrayList<Contact>
{
#Override
public boolean add(Contact c)
{
boolean result = super.add(c);
Collections.sort(this);
return result;
}
public ArrayList<Contact> search(String name)
{
// ...
}
}
By that you have a full-blown ArrayList and can extend it with what you need.
The other option is, to just kick out extends and just go for your own implementation of Contacts, utilizing the internal List as storage and not exposing it directly.
I think there is something wrong with your design.
I don't think you should extend ArrayList.
Because when you do it, your class IS an ArrayList, and also, you created an ArrayList object inside your class.
The thing is, when you called size, original ArrayList's size is being returned. Since you added the element to your ArrayList, the original is still empty.
You should use either delegation or inheritance, in this case you are mixing it both up.
Either implement java.util.List<Contact> (instead of extending ArrayList) and delegate every method call to the delegate (the class variable contacts)
OR
Remove the class variable contacts and use super.add() in your add method (instead of contacts.add()) and this instead of every other reference on contacts
I'm not sure how you read your file, but I seem to do just fine. In order to access the size of the contacts object in your factory, you need to call the 'size' method on the internal ArrayList instance variable, as opposed to calling on the 'contacts' object itself. In order to properly apply the 'size' method, it maybe that you need to override this method ('size') too.
Other than that, adding and retrieval seems fine. Check out the console output as well!
public class Contacts extends ArrayList<Contact>
{
private List<Contact> contacts = new ArrayList<Contact>();
#Override
public boolean add(Contact c)
{
contacts.add(c);
//Collections.sort(contacts);
return true;
}
#Override
public String toString()
{
return contacts.toString();
}
public List<Contact> getMyList()
{
return this.contacts;
}
public static void main(String[] args)
{
Contacts test=ContactsFactory.getContacts();
System.out.println(test.toString());
}
}
class ContactsFactory {
public static Contacts getContacts() {
String[] names={"A","B","C","D"};
int i=0;
Contacts contacts = new Contacts();
do {
System.out.println("Adding: "+names[i]);
contacts.add(new Contact(names[i]));
i++;
} while (i<names.length);
//print size to see anything added. It returns 0.
System.out.println(contacts.getMyList().size());
return contacts;
}
}
class Contact
{
String name;
#Override
public String toString()
{
return "Contact: "+this.name;
}
public Contact(String val)
{
this.name=val;
}
}
Output:
Adding: A
Adding: B
Adding: C
Adding: D
4
[Contact: A, Contact: B, Contact: C, Contact: D]

Copy ResolveInfo item from ArrayList a to ArrayList b?

Aasically I'm trying to add an item from ArrayList a (allApps) to ArrayList b (myApps) but I'm getting an error.
This is what I'm trying:
public ArrayList myApps = new ArrayList();
#Override
public void onCreate(Bundle savedInstanceState) {
...
for(final ResolveInfo app : allApps) {
addApp(app);
}
}
public void addApp(ResolveInfo app) {
ArrayList.add(app); // ERROR: Cannot make a static reference to the non-static method add(Object) from the type ArrayList
}
What does this error mean and how can I get I copy an item from one array to the other?
add method of ArrayList is not static method so you can not call outside an instance of ArrayList. Declare instance first then call add
it should be myApps.add(app);
You need to call add on an instance of ArrayList, not on the class itself, given your description, what you're looking for is
public void addApp(ResolveInfo app) {
myApps.add(app);
}
Change you method like this:
public void addApp(ResolveInfo app) {
myApps.add(app);
}

Categories

Resources