Increment each object's value by 11 inside a list - java

I have a list of objects where list name is employments and it has 'n' number of objects called employments.Each employment object has variable called serialnumber. Now i need to increment serialnumber for each object by 11.
Here is code
for(Employment employment:employments.getEmployemnts()){
if(employment="GENERAL_MANAGER"){
employement.setSerialNumberForGenManager()
}else{
employment.setSerialNumberForOthers()
}
Inside the employment class:
public static employemntIndex=11;
public employemnt setSerialNumberForGenManager(){
this.serialNumber = 0;
}
public employemnt setSerialNumberForOthers(){
this.serialNumber = employemntIndex+serialNumber;
}
Now,i'm not able to increment values by 11. The result for every object is always 11 only.It is not getting incremented.

This may be because of your String comparison. String comparisons should use the Object#equals(Object) method (as opposed to ==);
if (yourString.equals("COMPARISON STRING")) //do stuff
This is because String is an instance (which happens to contain text), and the the == operator in this case only tests the references, not whether the instances themselves contain the same text.
Also, = is an assignment operator, == should be used for most comparisons (other than 'special cases', such as comparing Strings).
The next problem is that you are not carrying the values over (as you say). To fix this;
public static employemntIndex = 11;
//Increase the employment index for each GENERAL_MANAGER
public employemnt setSerialNumberForOthers(){
this.serialNumber = employmentIndex;
employmentIndex += 11;
}

Try like this
public static Integer employemntIndex = 0;
public employemnt setSerialNumberForOthers(){
this.serialNumber = employemntIndex;
employemntIndex += 11;
}

Two possible errors:
You are using a so called "enhanced for loop".
You can't edit the elements of a collection that way as that loop is read-only.
To edit elements you have to use a for loop with an explicit iteration index or an iterator.
You seem to be comparing a reference (memory address with a String that is unlikely to correspond to a memory address.
employment="GENERAL_MANAGER"
You probably forgot to call a getter method like
employment.getRole().equals("GENERAL_MANAGER")
So it would be (if size() method is not supported you should use array.length)
for(int i = 0; i < employments.getEmployemnts().size(); i++) {
if(employments[i].yourGetter().equals("GENERAL_MANAGER")){
employements[i].setSerialNumberForGenManager()
}else{
employments[i].setSerialNumberForOthers()
}
Or if your collection implements the List interface
Iterator iter = employments.getEmployments().iterator();
while (iter.hasNext()){
Employment employment = iter.next();
if(employment.yourGetter().equals("GENERAL_MANAGER")){
employement.setSerialNumberForGenManager()
}else{
employment.setSerialNumberForOthers()
}
}
Hope that helped
Edit:
as KookieMonster has noticed you are using the assignment operator within the IF condition you should use the equals method

Related

Returning the index of a String parameter in an array

While I know that this code should work to return the index, for some reason it's skipping the if statement and going straight to the else, when I know that the name is within the array, with the array that I'm using for testing. Won't even print the "if - reading" line.
public int find(String name)
{
int index = 0;
for(int i = 0; i < this.shoppingItems.length;i++)
{
if(this.shoppingItems[i].equals(name))
{
System.out.println("If - Reading");
index = i;
}
else
{
index = -1;
}
}
System.out.println(index);
return index;
}
//Main
ShoppingItem[] items = new ShoppingItem[]{new ShoppingItem("Eggs",3.2),new ShoppingItem("Bread",2.8),new ShoppingItem("Bacon",9),new ShoppingItem("Peas",2),new ShoppingItem("Spinach",4),new ShoppingItem("Chocolate",8)};
ShoppingList itemList = new ShoppingList(items);
itemList.find("Bread");
"While I know that this code should work to return the index, for some reason it's skipping the if statement and going straight to the else"
Stop! Java is not wrong; your code is, and it shouldn't work. Your if statement is not being skipped; it's just that the condition is always false, because this.shoppingItems[i] is a ShoppingItem object, and you are comparing it with name, which is a string. A ShoppingItem object is never equal to a string.
Presumably, what you want to test is whether the ShoppingItem object's name is equal to that string. Presumably, your class has a getName method, so you should test:
if(this.shoppingItems[i].getName().equals(name)) {
// ...
}
This is a common kind of programming error, perhaps because it's often acceptable in natural language to say one thing when you mean something closely related; e.g. you might say "I asked the help desk" when really you asked a person at the help desk, you did not ask the desk itself. This is a bit like that; you want the item's name to equal name, not the item itself.
Unless you are compelled to use arrays, you can make things much easier by using lists. They have quite a few useful features.
List<String> items = List.of("bread", "juice", "eggs", "milk");
System.out.println(find("eggs"));
System.out.println(find("butter"));
public int find(String name) {
return items.indexOf(name);
}
Prints
2
-1
That method of the List interface pretty much negates the need to write you own method. I just did it for demonstration purposes.
This example was using a List of Strings and not ShoppingItem class. You could get a List<ShoppingItem> to work by overriding the equals method in your class (something you should get in the habit of anyway).
And here is a taste of how would do it with Stream (java 8+). It presumes list is a simple array of ShoppingItem.
public int find(String name) {
return IntStream.range(0, list.length).filter(
i -> list[i].item.equalsIgnoreCase(name)).findFirst().orElse(-1);
}

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.

How to return multiple conditions?

What should be my return at the end of my for loop? I'm trying to display the added results of all three parties numDemocrat, numRepulican and numIndepent by
calculating and then printing the number of democrats (party is "D"),
republicans (party is "R"), and independents (party is anything else).
I'm currently looping over the MemberOfCongress ArrayList returned by parseMembersOfCongress and counting up how many of each party type there are.
Also in my loop I need to check which party the current member belongs to and increment the proper variable. After the loop completes I then print the totals.
public void printPartyBreakdownInSenate()
{
CongressDataFetcher.fetchSenateData(congressNum);
}
{
ArrayList<MemberOfCongress> parseMembersOfCongress; String jsonString;
}
{
System.out.println("Number of Members of the Senate of the " + "&congressNum=" + "?chamber=");
}
public String[]
{
int numDemocrats = 0;
int numRepblican = 0;
int numIndepent = 0;
ArrayList<MemberOfCongress> members;
for (MemberOfCongress memberParty : members) {
if (memberParty.getParty() == "D" ) {
numDemocrats++;
}
else if (memberParty.getParty() == "R" ){
numRepblican++;
}
else if (memberParty.getParty() == "null"){
numIndepent++;
}
}
return ???;
}
Firstly i'm 99% positive you cannot return multiple values, unless your return either an array, an array list or a map.
But what you could do as a work around is one of the following.
1). Return a String array of party members.
2). Return a 2D array mapping name to age or something similar.
3). Return a hashmap of the data with a custom class of information mapped to a name.
4). Use getters to get different pieces of the data at time or all at once.
Java (like the majority of programmming languages) allows only a single return value from a method. There are lots of good reasons for this.
If you need to return multiple values then you will need a separate class for which your method can return a reference to an instance.
For example, in your case:
public enum Party {
REPUBLICAN, DEMOCRAT, OTHER;
}
public Map<Party, Integer> senatorsByParty(List<MemberOfCongress> senators) {
return senators.stream()
.collect(Collectors.groupingBy(MemberOfCongress::getParty, Collectors.counting()));
}
Apologies if you are not aware of the Java 8 syntax here. The stream functions are really just saying 'take all the senators, group them by party and then count them'. The key point is that you are returning a map from parties to integers representing the count of senators.

Setters and getters for Array of LinkedList

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

Categories