Setters and getters for Array of LinkedList - java

I have a class that called Entries that holds my constructor along with its getters and setters.
In a new class, I have :
private LinkedList<Entry>[] Entries = new LinkedList[26];
public void changeNumber(String number, String numberChange) {
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].getNumber().equals(number)){
myEntries[i].setNumber(numberChange);
break;
}
}
}
However, I am receiving errors for my setters and getters. This does not happen when I use a straight array or straight LinkedList, as I've already got this method working for those two in two different classes.
The error messages I'm receiving for both are
The method getNumber() is undefined for the type LinkedList
and The method getNumber() is undefined for the type LinkedList
I don't see why they're undefined as when I've tried doing the same method for a straight Array and a pure LinkedList, they've handled it fine and functioned properly.
If anyone has any suggestions, I would really appreciate it.

Pay close attention to the data type you're iterating over. Because myEntries is defined as a LinkedList<Entry>[], you're pulling out an individual LinkedList<Entry> when you iterate over the array.
It really seems like you don't want the array; instead, just iterate over the list elements directly:
LinkedList<Entry> myEntries = new LinkedList<>();
for(Entry entry : myEntries) {
if(entry.equals(number) {
// logic
}
}

myEntries[i] returns a LinkedList this doesnt have the setNumber method. You need to get the Entry out of the list and then invoke these methods.
myEntries[i].get(index).setNumber(); or myEntries[i].getFirst().setNumber(); etc

You are trying to call your accessors/mutators (getNumber() & setNumber) on the LinkedList instance and since there is no such methods for the LinkedList you will have the reported error.
So either get access to some LinkedList item with get() method that will return an Entry object on which you can call your setter and getter:
public void changeNumber(String number, String numberChange) {
int index = 0; //not sure what this index should be in your case
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].get(index).getNumber().equals(number)){
myEntries[i].get(index).setNumber(numberChange);
break;
}
}
}
Or better if you don't need the LinkedList, may be it is worth dropping you design and only create an Array of Entry:
private Entry[] entries = new Entry[26];
Then your changeNumber() method will be eligible:
public void changeNumber(String number, String numberChange) {
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].getNumber().equals(number)){
myEntries[i].setNumber(numberChange);
break;
}
}
}

Related

Making all values in an array unique

Im making a small school project, keep in mind i'm a beginner. Im gonna make a small system that adds member numbers of members at a gym to an array. I need to make sure that people cant get the same member number, in other words make sure the same value doesnt appear on serveral index spots.
So far my method looks like this:
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
if(memberNr.equals(mNr)){
throw new IllegalArgumentException("The member is already in the system");
}
else{
memberNr[count++] = mNr;
}
}
While having a contructor and some attributes like this:
int[] memberNr;
int arraySize;
int count;
public TrainingList(int arraySize){
this.arraySize = arraySize;
this.memberNr = new int[arraySize];
}
As you can see i tried using equals, which doesnt seem to work.. But honestly i have no idea how to make each value unique
I hope some of you can help me out
Thanks alot
You can use set in java
Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
mport java.util.*;
public class Set_example
{
public static void main(String[] args)
{
// Set deonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("a");
hash_Set.add("b");
hash_Set.add("a");
hash_Set.add("c");
hash_Set.add("d");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
// Set deonstration using TreeSet
System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
}
}
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
//You need to loop through your array and throw exception if the incoming value mNr already present
for(int i=0; i<memberNr.length; i++){
if(memberNr[i] == mNr){
throw new IllegalArgumentException("The member is already in the system");
}
}
//Otherwise just add it
memberNr[count++] = mNr;
}
I hope the comments added inline explains the code. Let me know how this goes.
Hey you can’t directly comparing arrays (collection of values with one integer value)
First iterate the element in membernr and check with the integer value

Shallow copy of object not correctly updating original object

I would like to model a graph, and to do so :
I have a class A that contains a LinkedList of instances of A and has a setter method associated :
class A {
private LinkedList<A> list;
[...]
public setList(LinkedList<A> l) {
this.list = l;
}
}
And in an other class NetA I have a method genCon that takes a LinkedList of instances of A then sets their list attribute to be a shuffled SubList of rlist :
static void genCon (LinkedList<A> rlist) {
for(int i=0; i<rlist.size(); i++) {
A temp = rlist.get(i);
LinkedList<A> slist = new LinkedList<A>(rlist.subList(0, rlist.size()));
temp.setList(slist);
}
}
Then genCon(rlist) is called in main, but altough all the objects of rlist should have their list initialized (and being equal to a shuffled version of rlist) some appear to be empty, with no consistent pattern (i.e. not every n or repeatable pattern), but completely at random.
At first I thought that A temp = rlist.get(i) was not giving me a shallow copy of the object at index i, but the check for identity with == returns true, so, if I am not mistaken that means that both variable hold the same reference and that should not be what is causing the issue?
Then I thought that it might be an optimization issue, maybe eclispe tries to do the operations in parallel and that somehow messes up the initialization at random?
I have tried to process step by step, but I can't seem to find where I messed up.
What did I miss?
Edit :
The main function looks like this :
public static void main(String[] args) {
LinkedList<A> a_list = generateAList(20);
genCon(a_list);
for(int i=0; i<a_list.size(); i++) {
System.out.println(a_list.get(i).toString());
}
}
a_list is correctly initialized. The issue happens in the following loop, when trying to print the objects.
Since it's only for testing main is located in the same class as genCon() atm.
generateAList() looks like this :
static public LinkedList<A> generateAList(int n) {
LinkedList<A> a_list = new LinkedList<A>();
for(int i=0; i<n; i++) {
ap_list.add(A.rand()); // A.rand() is just a static function that return an instance of A with randomly set values and an unitialized list.
}
return ap_list;
}

Java ArrayList trying to check if object with this name exists

I'm having a bit of trouble in my head trying to solve this:
I'm working on a "rankList", an arrayList made of "Score". Score it's the object that has the following atributes: name,wins,loses,draws. My class Ranking has an ArrayList of Score objects. To create a new Score object I just use the name (and set the rest to 0 since it's new). However I'm trying to check if the player's name it's already in rankList I don't have to create new but sum a win or lose or draw.
I have been reading arround that I have to override equals then others say I have to override contains... It's getting a big mess in my head. My fastest solution would be to write an "for" that goes arround the arrayList and use the getName().equals("name"); however this is getting too messi in my code. I have checkPlayer (if the palyer is in the list):
public boolean checkPlayer(String playerName) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
return true;
}
}
return false;
}
then if I want to incrase the wins i have this :
public void incraseWins(String playerName) {
if (checkPlayer(playerName)) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
} else {
createPlayer(playerName);
//more for to get to the player i'm looking for...
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
}
So i guess there is a better way to do this... :/
ArrayList is not the right data structure here. To check if an element exists in the array you are searching the entire arraylist. Which means it's O(N).
To keep an array list is sorted order and do a binary search on it would definitely be faster as suggested in the comments. But that wouldn't solve all your problems either because insert into the middle would be slow. Please see this Q&A: When to use LinkedList over ArrayList?
One suggestion is to use a Map. You would then be storing player name, player object pairs. This would give you very quick look ups. Worst case is O(log N) i believe.
It's also worth mentioning that you would probably need to make a permanent record of these scores eventually. If so an indexed RDBMS would give you much better performance and make your code a lot simpler.
Try using a hashtable with a key, it would be much more efficient!
e..Why not using map<>.
a binary search is good idea if you must use List,code like this
List<Method> a= new ArrayList<>();
//some method data add...
int index = Collections.binarySearch(a, m);
Method f = a.get(index);
and class method is impl of Comparable,then override compareTo() method
public class Method implements Comparable<Method>{
........
#Override
public int compareTo(Method o) {
return this.methodName.compareTo(o.getMethodName());
}
if you don't want use binsearch,CollectionUtils in commons can help you
CollectionUtils.find(a, new Predicate() {
#Override
public boolean evaluate(Object object) {
return ((Method)object).getMethodName().equals("aaa");
}
});
in fact CollectionUtils.find is also a 'for'
for (Iterator iter = collection.iterator(); iter.hasNext();) {
Object item = iter.next();
if (predicate.evaluate(item)) {
return item;
}
}

Android II JAVA Sorting An ArrayList of an object

First of all sorry if my English bad, its not my first language..
I'm working on and android app project, that needed to sort ArrayList of an object..so I made this method to deal with that...
Lets say that I have an object of Restaurant that will contain this data:
private String name;
private float distance ;
And I sort it using the value of the variable distance from lowest to highest:
public void sort(RArrayList<RestaurantData> datas) {
RestaurantData tmp = new RestaurantData();
int swapped;
boolean b = true;
while (b) {
swapped = 0;
for (int i = 0; i < datas.size()-1; i++) {
if (datas.get(i).getDistance() > datas.get(i+1).getDistance()) {
tmp = datas.get(i);
datas.set(i, datas.get(i+1));
datas.set(i+1, tmp);
swapped = 1;
System.err.println("Swapped happening");
}
}
if (swapped == 0) {
System.err.println("Swapped end");
break;
}
}
But when i try the program..the result of an ArrayList is still random, is there any problem with my logic to sort the ArrayList of an object..
Please Help...Thankyou..
Why not use the Collections.sort method?
Here's how you could do it in your project:
public void sort(RArrayList<RestaurantData> datas) {
Collections.sort(datas, new Comparator<RestaurantData>() {
#Override
public int compare(RestaurantData lhs, RestaurantData rhs) {
return lhs.getDistance() - rhs.getDistance();
}
});
}
The above solution is a bit "destructive" in the sense that it changes the order of the elements in the original array - datas. If that's fine for you go ahead and use it. Personally I prefer things less destructive and if you have the memory to spare (meaning your array is small) you could consider this solution which copies the array before sorting. It also assumes your RArrayList is an implementation of ArrayList or backed up by it:
public List<RestaurantData> sort(RArrayList<RestaurantData> datas) {
// Create a list with enough capacity for all elements
List<RestaurantData> newList = new RArrayList<RestaurantData>(datas.size());
Collections.copy(newList, datas);
Collections.sort(newList, new Comparator<RestaurantData>() {
#Override
public int compare(RestaurantData lhs, RestaurantData rhs) {
return lhs.getDistance() - rhs.getDistance();
}
});
return newList;
}
Another thing to consider is also to create a single instance of the Comparator used in the method, since this implementation will create one instance per call. Not sure if it's worth it though, because it will also be destroyed quite soon since the scope is local.
Here's the documentation for the Collections api
One last thing, the comparator simply needs to return a value less than 0 if the elements are in the right order, bigger than 0 if they're in the wrong order or 0 if they're the same. Therefore it seems to be that it's enough to simply subtract the distances of each restaurant. However, if this isn't the case, please implement the comparator suiting your needs.

I get a compile time error when accessing an ArrayList with a new method

I am attempting to access an ArrayList that was created in a different method within the same class. The scanner method pulls in data from a text file. The text file data appears this way: 123 12 1 43, with line breaks...
Currently, my method works to pull in the data, but does not compile after that method ends. I originally had the entire code within the same method and it worked fine. But I'd like to return the largest value by creating a new method within this class, and then create a tester class that will access this new method. Here is my existing code. Or if there is a better solution. I'm all ears.
public class DataAnalyzer {
public DataAnalyzer(File data) throws FileNotFoundException
{
List<Integer> rawFileData = new ArrayList<>();
FileReader file = new FileReader("info.txt");
try (Scanner in = new Scanner(file)) {
while(in.hasNext())
{
rawFileData.add(in.nextInt());
}
}
}
public int getLargest(rawFileData){
int largest = rawFileData.get(0);
for (int i = 1; i < rawFileData.size(); i++){
if (rawFileData.get(i) > largest)
{
largest = rawFileData.get(i);
}
}
for (Integer element : rawFileData){
if (element == largest)
{
System.out.print("This is the Largest Value: ");
System.out.print(element);
}
}
}
}
Your main issue is with your method declaration. It needs a type parameter:
public int getLargest(List<Integer> rawFileData)
Note the List<Integer>.
Now, there is already a method for this in the Collections utility class. You would do well to look over that link in detail - there are many useful methods there. To get the highest element from a Collection of Objects that have a natural order (such a Integer). For example
int largest = Collections.max(rawFileData)
So your method can be reduced to:
public int getLargest(List<Integer> rawFileData)
return Collections.max(rawFileData);
}
You need to think over your logic much more carefully before you begin to write code, for example, your first loop is good:
int largest = rawFileData.get(0);
for (int i = 1; i < rawFileData.size(); i++){
if (rawFileData.get(i) > largest)
{
largest = rawFileData.get(i);
}
}
You do exactly what any programmer would do. But then, instead of returning the largest when you find it, you for some reason loop again:
for (Integer element : rawFileData){
if (element == largest)
{
System.out.print("This is the Largest Value: ");
System.out.print(element);
}
}
Ask yourself what does this do? You have a List of, say, apples. You look at each one and compare them - finding the largest apple. You now have the largest apple in the List. You then loop over the List again looking for an apple that matches the apple you have already found. Why do this?
Further, you never return from the method. Your method is declared as returning an int; but you never do.
The missing type in your method definition is the problem here.
Change the method definition from
public int getLargest(rawFileData) {
....
}
to
public void getLargest(List<Integer> rawFileData) {
....
}
And the second for loop in the method is unnecessary. The largest integer is already stored in the variable "largest" and you can print it after the first for loop.

Categories