I create two classes. The first one (call it Class1) has one private attribute: price. The second one (call it Class2) needs to have a set of objects of Class1:
My code:
private HashSet set = new HashSet<Class1>();
The goal is to create a method in the Class2, which takes an int as an argument and goes through objects to check until it finds one, which has a price equal to a given as an argument number. It needs to return the object. For example, I want to find an object with a price of 500, so I call the function check(500) and it returns exactly that object, which has price of 500. How can I do it?
My code:
public Class1 check(int p)
{
Class1 c = new Class1(p);
Iterator it = set.iterator();
while(it.hasNext())
{
// HERE IS THE HELP NEEDED. Using an array it
// would be sth like if(element[i].price == p)
// but I need to use set
if()
{}
it.next();
}
You can do it like so - however you will need access to the price to be able to compare it. If price itself is private, there should be a getter for it, which I assume in my solution.
public Class1 check(int p) {
for (Class1 c : set) {
if (c.getPrice() == p) return c;
}
return null; // none found
}
In your class Class1, define a getter method
int getPrice() { return price; }
Use it in your class Class2
Class1 curObj = it.next();
if (curObj.getPrice() == p) {
your logic
}
Something like this should work:
public Class1 check(int p) {
Iterator<Class1> it = set.iterator();
while (it.hasNext()) {
Class1 next = it.next();
if (next.getPrice() == p) {
return next;
}
}
return null;
}
I assumed your class Class1 has a getPrice method that returns the price, it is ofcourse impossible to compare the price that we need to find to the price of an object if there is no way to access the field.
Your generic type declaration is incorrect and thus you have a raw type; and you should prefer the Set interface. Something like
private Set<Class1> set = new HashSet<>();
And you can use an enhanced for-each loop to iterate your set items and find a matching price with something like
public Class1 check(int p) {
for (Class1 item : set) {
if (item.getPrice() == p) {
return item;
}
}
return null;
}
Whenever you have private variables, expose them through getter function.
Setters and getters will always help you whenever you will write code with some frameworks like Spring, Hibernate, etc.
public class class2 {
private HashSet set = new HashSet<Class1>();
public Class1 check(int price) {
Iterator<Class1> iterator = set.iterator();
while(iterator.hasNext()) {
Class1 next = iterator.next();
if(next.getPrice() == price)
return next;
}
return null;
}
}
class Class1 {
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
You can it iterate the set and in every iteration compare the object against the price parameter, if found return the object, if not return null
Example
public Class1 check(int p)
{
for(Class c : set){
if(c.getPrice ()==p){
return c;
}
}
return null;
}
Add a getter of the price attribute in class1, then the check method can be as follows:
public Class1 check(int p)
{
for (Class1 c1 : set)
{
if (c1.getPrice() == p)
return c1;
}
return null
}
Related
Long story short, main class consist of
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Car r1 = new Car(1000, true); ...
Cars class is subClass of Vehicles superclass and objects are added to vehicles list. Lastly, the main class calls out
System.out.println(Car.findMostExpensive4x4(vehicles).getPrice());
SubClass "Car" constructor takes in 2 parameters - price and the 4x4 (boolean)
public Car(double pPrice, boolean pfourByFour) {
super(pPrice);
this.fourByFour = pfourByFour;
}
The method that is called out in main has to parse data from object list and return that object. But how is this implemented ?
public static Car findMostExpensive4x4(List<Vehicle> vehicles) {
}
Then, the returned Car object price is found by getPrice method somehow.
public double getPrice() {
return 0;
}
Thank you
The list passed as argument cannot be a Vehicles list, since a Vehicle doesn't know if is 4x4 or not. Cars knows it.
You can create a Vehicle interface:
interface Vehicle {
double getPrice();
boolean is4x4();
}
class Car implements Vehicle {
private double price;
private boolean is4x4;
public Car(double price, boolean is4x4) {
this.price = price;
this.is4x4 = is4x4;
}
#Override
public double getPrice() {
return price;
}
#Override
public double is4x4() {
return is4x4;
}
public static Car findMostExpensive4x4(List<Vehicle> vehicles) {
if (vehicles == null) return null; //or throw exception
if (vehicles.isEmpty()) return null; // or throw exception
double mostExpensivePrice = 0d;
Vehicle mostExpensive = null;
for (Vehicle v : vehicles) {
if (v.is4x4() && v.getPrice() > mostExpensivePrice) {
mostExpensive = v;
mostExpensivePrice = v.getPrice();
}
}
return mostExpensive != null? (Car)mostExpensive : null;
}
}
It is supposed that price cannot be less than 0. In another case, this solution is not valid.
return (Car)mostExpensive; will fail if vehicle is not a Car.
findMostExpensive4x4 method shouldn't be placed in Car class.
This is a fast-thought solution and very ugly, too. You should consider to re-think the design.
I am trying to develop a program that can sort an array of objects that are of different class types, but in the same hierarchy as one another. All of the objects are listed within the same array that I am trying to sort, and while I can alphabetically sort an array of objects that are of the same type easily enough, I cannot figure out how to sort everything all at once with the same Arrays.sort() method. Any help that anyone could provide would be greatly appreciated.
import java.util.Arrays;
public class Driver {
public static void main(String[] args) {
Vehicle[] machines = new Vehicle[3];//Example of an array that I can sort
machines[0] = new Vehicle("Giant Robot");
machines[1] = new Vehicle("Time Machine");
machines[2] = new Vehicle("Airplane");
Arrays.sort(machines);
for (int i = 0; i < machines.length; i++)
System.out.println(machines[i].getName());
Vehicle[] vehicles = new Vehicle[7];//example of an array that I cannot sort
vehicles[0] = new Car("Batmobile", 10);
vehicles[1] = new Helicopter("Batcopter", "x");
vehicles[2] = new Car("Jaguar", 6);
vehicles[3] = new Helicopter("RC Copter", "t");
vehicles[4] = new Car("Accelerator", 6);
vehicles[5] = new Helicopter("Stormshadow", "z");
vehicles[6] = new Car("Batmobile", 11);
}
}
**
public class Vehicle implements Comparable {
private String name;
public Vehicle(){
name = "no name";
}
public Vehicle(String newName){
name = newName;
}
public String getName(){
return name;
}
public int compareTo(Object o)
{
if ((o != null) &&
(o instanceof Vehicle))
{
Vehicle otherVehicle = (Vehicle) o;
return (name.compareTo(otherVehicle.name));
}
return -1;
}
}
**
public class Car extends Vehicle {
private int tireSize;
public Car(){
super();
tireSize = 0;
}
public Car(String newName, int newTireSize){
super(newName);
tireSize = newTireSize;
}
public int getSize(){
return tireSize;
}
}
**
public class Helicopter extends Vehicle {
private String bladeType;
public Helicopter(){
super();
bladeType = "none";
}
public Helicopter(String newName, String newBlade){
super(newName);
bladeType = newBlade;
}
public String getType(){
return bladeType;
}
}
Goal: You need to be able to compare a Vehicle to other of Vehicle.
To achieve that goal:
public class Vehicle implements Comparable<? extends Vehicle> {
....
public int compareTo(Object o) {
// Now, that the Comparable is for the type Vehicle
// you know that o is some kind of vehicle
// check vehicle related things
// number of seats, dogs, whatever
return -1;
}
}
You just need to adjust your code to:
class Vehicle implements Comparable<Vehicle> {
private String name;
/* ... */
#Override
public int compareTo(Vehicle vehicle) {
return name.compareTo(vehicle.getName());
}
}
In most cases, your classes should not implement Comparable, unless there is one and only one ordering that is always the correct one, like with numbers. Your vehicles can be sorted by name, by age, and probably by more criteria, so they should not implement Comparable.
Instead, you can pass the ordering function as a lambda function, at the time where you actually sort your vehicles:
Arrays.sort(machines, (left, right) -> left.getName().compareTo(right.getName()));
Or, equivalently:
Arrays.sort(machines, Comparator.comparing(Vehicle::getName));
This way you don’t need the implements Comparable anymore.
If you want to sort by vehicle type then you need to take class type into consideration, while sorting the element. Modify the compareTo() method as shown below:
public int compareTo(Object o){
if ((o != null) &&
(o instanceof Vehicle)){
Vehicle otherVehicle = (Vehicle) o;
return (otherVehicle.getClass().getSimpleName().equals(this.getClass().getSimpleName()) ?
name.compareTo(otherVehicle.name)
: otherVehicle.getClass().getSimpleName().compareTo(this.getClass().getSimpleName()));
}
return -1;
}
I am creating a demo shopping cart in android for this i am using Application class for saving data. I am unable to delete data from linkedlist. I am calling removeItem() function for android activity for removing selected item from the list but it is not working any one can help me.
package in.co.santoshsharma.bookshopping;
import java.util.LinkedList;
import android.app.Application;
import android.content.res.Configuration;
public class GlobalData extends Application{
private String email;
private String itemName;
private int itemQuantity;
private int itemCost;
public GlobalData(){
}
public GlobalData(String iName,int iQunt,int iCost) {
// TODO Auto-generated constructor stub
this.itemCost=iCost;
this.itemName=iName;
this.itemQuantity=iQunt;
}
public void setEmail(String mail)
{
this.email=mail;
}
public String getEmail()
{
return email;
}
public String getItemName()
{
return itemName;
}
public int getItemCost()
{
return itemCost;
}
public int getItemQunt()
{
return itemQuantity;
}
LinkedList<GlobalData> list = new LinkedList<GlobalData>();
public void setList(String iName,int iQunt,int iCost)
{
list.add(new GlobalData( iName, iQunt, iCost));
}
public LinkedList<GlobalData> getList()
{
return list;
}
public void removeItem(String iName,int iQunt,int iCost)
{
for(GlobalData data:list)
{
if(data.getItemName().equals(iName))
{
list.remove(itemName);
//list.remove(iCost);
//list.remove(iQunt);
}
}
}
}
First, override equals() method and use itemName attribute for the comparison
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (itemName == null) return false;
if (o instanceOf String) return itemName.equals(o);
else if (o instanceOf GlobalData) return ((GlobalData) o).itemName.equals(this.itemName);
else return false;
}
Then, change your removeItem() method
public void removeItem(String iName) {
list.remove(iName);
// or uncomment line below to completely remove all matching elements
// for (;;list.remove(iName)) {}
}
According to http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html#remove(java.lang.Object) remove() method of a LinkedList will call the equals() method of the supplied Object and compare it with every element in the list.
Hope this helps :)
you cannot operate in lists (add, remove... items) while you iterate on them. You have to use an Iterator
for(Iterator<EmpDedup> iter = list.iterator(); iter.hasNext();) {
EmpDedup data = iter.next();
if (data.getRecord() == rec1) {
iter.remove();
}
}
see http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html
Refered from https://stackoverflow.com/a/10735435/1602230
Use a iterator to remove the element:
public void removeItem(String iName, int iQunt, int iCost) {
Iterator<GlobalData> iterator = list.iterator();
while (iterator.hasNext()) {
GlobalData data = iterator.next();
if (data.getItemName().equals(iName)) {
iterator.remove();
}
}
}
- You are Concurrently accessing and modifying the Collection, that can't be done from For-Each loop directly..
- Use Iterator to solve this problem.
LinkedList<GlobalData> q1 = new LinkedList<GlobalData>();
Iterator<GlobalData> iterator = q1.iterator();
while (iterator.hasNext()){
GlobalData mp = iterator.next();
if (mp.name.equals("xyz")){
iterator.remove(); // You can do the modification here.
}
}
You cannot modify a Collection using for-each loop. Use simple for loop or while.
The for-each loop hides the iterator, so you cannot call remove.
Therefore, the for-each loop is not usable for filtering. Similarly it
is not usable for loops where you need to replace elements in a list
or array as you traverse it.
Source: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Generally, a collection named list storing elements of type E uses an iterator in the following way:
Iterator<E> iterator = list.iterator();
while(iterator.hasNext()) {
<do something with iterator.next()>;
}
I've got a public List<FriendProfile> friends = new ArrayList<FriendProfile>();. I initialize the friends list by reading the information from the server. The FriendProfile object contains a int called private int userPosition;
Once the friends list has been initialized, I would like to sort the friends list by having the FriendProfile object with the highest userPosition at index 0 of the list and then sort by accordingly, index 1 with the second highest userPosition ...
I guess I could write an sorting algorithm, yet I'm looking for prewritten code (maybe the JDK has some methods to offer?)
Help is appreciated!
Use Collections.sort() and specify a Comparator:
Collections.sort(friends,
new Comparator<FriendProfile>()
{
public int compare(FriendProfile o1,
FriendProfile o2)
{
if (o1.getUserPosition() ==
o2.getUserPosition())
{
return 0;
}
else if (o1.getUserPosition() <
o2.getUserPosition())
{
return -1;
}
return 1;
}
});
or have FriendProfile implement Comparable<FriendProfile>.
Implement Comparable Interface.
class FriendProfile implements Comparable<FriendProfile> {
private int userPosition;
#Override
public int compareTo(FriendProfile o) {
if(this.userPosition > o.userPosition){
return 1;
}
return 0;
}
}
Just Call the Collection.sort(List) method.
FriendProfile f1=new FriendProfile();
f1.userPosition=1;
FriendProfile f2=new FriendProfile();
f2.userPosition=2;
List<FriendProfile> list=new ArrayList<FriendProfile>();
list.add(f2);
list.add(f1);
Collections.sort(list);
The List will be sorted.
Now no need to Boxing (i.e no need to Creating OBJECT using new Operator use valueOf insted with compareTo of Collections.Sort..)
1)For Ascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
}
});
1)For Deascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
}
});
Use Collections.Sort and write a custom Comparator that compares based on userPosition.
use Comparator with Collections.sort method
java.util.Collections.sort(list, new Comparator<FriendProfile >(){
public int compare(FriendProfile a, FriendProfile b){
if(a.getUserPosition() > b.getUserPosition()){
return 1;
}else if(a.getUserPosition() > b.getUserPosition()){
return -1;
}
return 0;
}
});
see this link
There are two ways to do this.
1.
FriendProfile could implement the interface Comparable.
public class FriendProfile implements Comparable<FriendProfile>
{
public int compareTo(FriendProfile that)
{
// Descending order
return that.userPosition - this.userPosition;
}
}
...
Collections.sort(friendProfiles);
2.
You could write a Comparator.
public class FriendProfileComparator implements Comparator<FriendProfile>
{
public int compare(FriendProfile fp1, FriendProfile fp2)
{
// Descending order
return fp2.userPosition - fp1.userPosition;
}
}
...
Collections.sort(friendProfiles, new FriendProfileComparator());
When comparing objects rather than primitives note that you can delegate on to the wrapper objects compareTo. e.g. return fp2.userPosition.compareTo(fp1.userPosition)
The first one is useful if the object has a natural order that you want to implement. Such as Integer implements for numeric order, String implements for alphabetical. The second is useful if you want different orders under different circumstances.
If you write a Comparator then you need to consider where to put it. Since it has no state you could write it as a Singleton, or a static method of FriendProfile.
You can use java.lang.Comparable interface if you want to sort in only One way.
But if you want to sort in more than one way, use java.util.Compartor interface.
eg:
The class whose objects are to be Sorted on its roll_nos
public class Timet {
String name;
int roll_no;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getN() {
return roll_no;
}
public void setN(int n) {
this.roll_no = n;
}
public Timet(String name, int n) {
this.name = name;
this.roll_no = n;
}
public String toString(){
return this.getName();
}
}
The class for sorting:
public class SortClass {
public void go(){
ArrayList<Timet> arr = new ArrayList<Timet>();
arr.add(new Timet("vivek",5));
arr.add(new Timet("alexander",2));
arr.add(new Timet("catherine",15));
System.out.println("Before Sorting :"+arr);
Collections.sort(arr,new SortImp());
System.out.println("After Sorting :"+arr);
}
class SortImp implements Comparator<Timet>{
#Override
public int compare(Timet t1, Timet t2) {
return new Integer(t1.getN()).compareTo (new Integer((t2.getN())));
}
}
public static void main(String[] args){
SortClass s = new SortClass();
s.go();
}
}
I am sure this is a very easy question for many, but I am struggling with it. I am trying to get a value from the following constructor and place it in a vector.
Each time I add the object to the vector though, the value that is placed inside the vector is null. How can I get the number to be the value that is placed into the vector?
The CInteger class:
public class CInteger
{
private int i;
CInteger(int ii)
{
i = ii;
}
}
And in my A1 class, the constructor and my attempt at getting the value:
Object enqueue(Object o)
{
CInteger ci = new CInteger(88);
Object d = ??
add(tailIndex, d);// add the item at the tail
}
Thank you all for any insight and help, I am still learning.
EDIT: SOLVED
CInteger class:
public class CInteger implements Cloneable // Cloneable Integer
{
int i;
CInteger(int ii)
{
this.i = ii;
}
public int getValue()
{
return i;
}
}
Both enqueue methods:
public void enqueue(CInteger i) // enqueue() for the CInteger
{
add(tailIndex, new Integer(i.getValue())); get int value and cast to Int object
}
public void enqueue(Date d) // enqueue() for the Date object
{
add(tailIndex, d);
}
Thank you very much everyone. :D
You can simply overload the enqueue class to take both Dates and Integers. In either case, it sounds like you need a method getValue() in CInteger that lets you access the int value.
public class CInteger
{
//constructors, data
public void getValue()
{
return i;
}
}
and then you can have two enqueue() methods in your other class:
public void enqueue(Date d)
{
add(tailIndex, d);
}
public void enqueue(CInteger i)
{
add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object
}
And Java will know which one you are calling automatically based on the parameters.
It is not entirely clear what you are actually trying to do, but I think that this will suffice:
Object enqueue() {
CInteger ci = new CInteger(88);
add(tailIndex, ci);// add the item at the tail
return ci; // this will automatically upcast ci as an Object
}
Try this.
public class CInteger {
private int i;
CInteger(int ii) {
this.i = ii;
}
}
Using the this Keyword
First of all, Constructors never return any value. You have to access the value through its objects or you have to use getter methods.
In your case, "private int i;" can not be accessed directly. So try make either it as public or have some getter method.
So try it:
CInteger ci = new CInteger(88);
Object d = ci.i; // if i is public member
add(tailIndex, d);
or
...
private int i;
...
public int getI() {
return this.i;
}
...
CInteger ci = new CInteger(88);
Object d = ci.getI();
add(tailIndex, d);
Wouldn't it just be:
void main(string[] args)
{
CInteger ci = new CInteger(88);
encqueue(ci.i);
}
Object enqueue(Object o)
{
add(tailIndex, o);
}
Or am I missing something?