All im trying to do is reverse the ArrayList. Is there a way I could do it through the toString as well or should I just create a method like I did. Im so close, any answers will help! Thanks!
package edu.purse.test;
java.util.ArrayList;
import java.util.Collections;
public class Purse
{
ArrayList<String> coins = new ArrayList<String>();
public Purse()
{
}
public void addCoin(String coinName)
{
coins.add(coinName);
}
public String toString()
{
return "Purse" + coins.toString();
}
public ArrayList<String> getReversed(ArrayList<String> coins)
{
ArrayList<String> copy = new ArrayList<String>(coins);
Collections.reverse(copy);
return copy;
}
}
TESTERCLASS
package edu.purse.test;
import java.util.Collections;
import java.util.List;
public class PurseTester {
public static void main(String[] args) {
Purse p = new Purse();
p.addCoin("Quarter");
p.addCoin("Dime");
p.addCoin("Nickel");
p.addCoin("Penny");
System.out.println(p.toString());
p.getReversed(coins);
}
}
The method
p.getReversed(coins);
returns a reversed list. You can just print it out
System.out.println(p.getReversed(coins));
Note that you are getting a copy of your instance's list, reversing that, and then returning it. If you want to preserve the change, simple call Collections.reverse() on the original, coins.
Related
I was running the below code
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
class Ca implements Comparator<CollectionAndClass>{
public int compare(CollectionAndClass a,CollectionAndClass b){
return a.roll-b.roll;
}
}
public class CollectionAndClass {
int roll;
int dar;
public CollectionAndClass(int a,int b) {
roll=a;
dar=b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<CollectionAndClass> link=new LinkedList<CollectionAndClass>();
CollectionAndClass d=new CollectionAndClass(4,5);
link.add(d);
link.add(new CollectionAndClass(5,6));
d.roll=d.dar=1;
link.add(d);
Collections.sort(link, new Ca());
Iterator<CollectionAndClass> itr=link.iterator();
while(itr.hasNext()) {
System.out.println(itr.next().roll);
}
}
}
and i got the output:
1
1
5
I think the output should be 1 4 5 but it is 1 1 5. I don't what's the mistake in my code.
You added d twice to list and you change its roll value to 1
It effects object properties even it d was already added to list before
For expected results add a new instance instead of d:
link.add(new CollectionAndClass(1, 5));
Hey I have modified your code to get the desired output.
package com.dream11.contest;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
class Ca implements Comparator<CollectionAndClass>{
public int compare(CollectionAndClass a,CollectionAndClass b){
return a.roll-b.roll;
}
}
public class CollectionAndClass {
int roll;
int dar;
public CollectionAndClass(int a,int b) {
roll=a;
dar=b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<CollectionAndClass> link=new LinkedList<CollectionAndClass>();
CollectionAndClass d=new CollectionAndClass(4,5);
link.add(d);
link.add(new CollectionAndClass(5,6));
//d.roll=d.dar=1; You are modifying the same object d, it is reference to object added in list, hence any modification via d will also reflect in the list
// link.add(d); and adding same object again
CollectionAndClass d2=new CollectionAndClass(1,1); // instead create a new object , with new set of values
link.add(d2); // add in the list
Collections.sort(link, new Ca());
Iterator<CollectionAndClass> itr=link.iterator();
while(itr.hasNext()) {
System.out.println(itr.next().roll);
}
}
}
The variable d is basically reference to the object, hence any modification you do using the reference d will modify the same object and the changes will get reflected in the list
today I'm making a Minecraft java mod
I made a custom command list using
public String Commands[];
but later I tried to add a string using
Commands.add("");
why
the primary array is different from object ArrayList/LinkedList, which implements List.
method add() is belong to implement List;
List<String> commands = new ArrayLidt<>();
commands.add("whatever");
or
String[] commands = new String[SIZE];
commands[0] = "";
Sample usage for string arraylist implementation:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> supplierNames = new ArrayList<>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
for (String supply : supplierNames) {
System.out.println(supply);
}
}
}
Trying to get the person ArrayList passed from oca project to the main form then pass the list to the assign bonus form. It passes to the main form correctly but can't seem to get seem to retrieve the ArrayList in assign bonus. Every time it runs I get an error saying out of bounds error from the system.out part when trying to get 1 of the person list.
package oca.project;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class OCAProject {
static ArrayList<Person> persons = new ArrayList<>();
public static void main(String[] args) {
CEO JamesMint = new CEO();
//making objects
AdministrationManager BillJohns = new AdministrationManager(JamesMint);
FinancialAdministrator EricWhite = new FinancialAdministrator(JamesMint);
persons.add(JamesMint);
persons.add(BillJohns);
persons.add(EricWhite);
//declaring form and passing arraylist as parameter
MainForm frame = new MainForm(persons);
frame.setVisible(true);
}
}
main form class
package oca.project;
import java.util.ArrayList;
public class MainForm extends javax.swing.JFrame {
//array list to hold the report items
private ArrayList<PayrollReportItem> payRolllist = new ArrayList<>();
AssignBonusForm assignFrame = new AssignBonusForm(payRolllist);
void setList(ArrayList<Person> persons) {
//sets arraylist
assignFrame.setPersons(persons);
}
public MainForm(ArrayList<Person> persons) {
initComponents();
setList(persons);
}
private void btnAssignBonusActionPerformed(java.awt.event.ActionEvent evt) {
//to open assign bonus form
assignFrame.setVisible(true);
this.dispose();
}
assign bonus form
package oca.project;
import java.util.ArrayList;
public class AssignBonusForm extends javax.swing.JFrame {
ArrayList<Person> persons = new ArrayList<>();
public AssignBonusForm(ArrayList<PayrollReportItem> payRolllist) {
initComponents();
System.out.println(persons.get(1));
}
private AssignBonusForm() {
}
public void setPersons(ArrayList<Person> persons) {
this.persons = persons;
}
public ArrayList<Person> getPersons() {
return persons;
}
I'm not entirely sure that this is the issue (since I don't know Java THAT in depth), but perhaps in MainForm, you are calling the constructor to AssignBonusForm before you set the list? I'm not entirely sure if member data is initialized first or if the constructor is called first, but if member data is initialized first, then the issue is that you haven't set the value of payRolllist when you called the AssignBonusForm constructor. Hope this helps :)
I have an ImmutableSortedSet that is create on initialization of a class. For every object of this class i want the ImmutableSortedSet to have a deep copy (clone) of the elements stored in an Collection located in another file.
This is the collection with the original values (could also be a set)
public static final List<Quest> QUESTS = new ArrayList<>();
This is the class i want to create with the ImmutableSortedSet
package com.vencillio.rs2.content.quest;
import java.util.Optional;
import java.util.Set;
import com.google.common.collect.ImmutableSortedSet;
public class QuestManager {
private int questPoints = 0;
private final Set<Quest> QUESTS = ImmutableSortedSet.copyOf(Quest.QUESTS); //This is only a shallow copy
public int getQuestPoints() {
return questPoints;
}
public void addQuestPoints(int amount) {
questPoints += amount;
}
public void removeQuestPoints(int amount) {
questPoints -= amount;
}
public Optional<QuestState> getQuestState(String name) {
return getQuest(name).isPresent() ? Optional.of(getQuest(name).get().getQuestState()) : Optional.empty();
}
public void setQuestState(String name, QuestState state) {
if(getQuest(name).isPresent())
getQuest(name).get().setQuestState(state);
}
public Optional<Quest> getQuest(String name) {
return QUESTS.stream().filter(quest -> quest.getName().equalsIgnoreCase(name)).findAny();
}
}
You haven't explained how to get a copy of a Quest in the first place, which is an aspect of your design. In general, I'd write something like
import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet;
import static java.util.Comparator.naturalOrder;
Quest.QUESTS.stream()
.map(quest -> copy(quest))
.collect(toImmutableSortedSet(naturalOrder()));
I have an Array that is in a class called MusicArray
and I want to be able to print its data and search it in my SearchClass class
import java.util.Arrays;
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
MusicArray ma = new MusicArray();
for(int count = 1; count <= songDetails.length; count++){
System.out.println(SongDetails.length);
System.out.println(songDetails[count - 1]);}
In the MusicArray class I have this
public Music[] getSongDetails() {
return songDetails;
I though that this code snippet made the array availabe to the other classes
What am I missing?
You need to use the ma object to retrieve the array, like this:
Music[] songDetails = ma.getSongDetails();
Then you can iterate over the Music[] array.
You should use ma.getSongDetails() to access the array from your SearchClass.
import java.util.Arrays;
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
MusicArray ma = new MusicArray();
Music [] details = ma.getSongDetails();
for(int count = 0; count < details.length; count++)
{
System.out.println(details.length);
System.out.println(details[count]);
}
}
}
Unfortunately, this code will probably still have problems. You don't add any instances of Music to MusicArray, so either the array will be null (you'll see a NullPointerException) or empty (nothing will print.)