HashMap find() with arrays - java

I have a class named Machine defined as :
class Machine
{
private String name;
Machine() { name = null; }
// set , get methods of String name
}
I also have a class named MachineAtt implementing an interface Att like:
// Att interface
interface Att
{
void add(Machine obj);
Machine find(String name)
}
// MachineAtt class
class MachineAtt implements Att
{
protected Map<String,Machine> hashTable = new HashMap<String,Machine>();
// ovveride methods from interface Att
}
the main function is:
Machine car = new Machine();
car.setName("MB");
//create an object of MachineAtt
MachineAtt foundit = new MachineAtt();
foundit.add(car);
foundit.find("MB");
My question is: how can I do the same but with an array?
for example, I want to foundit.add(someArray) and then I search certain item in this array by using method find(); I hope you get what I mean. Any ideas?

Your addAll(Machine[] machines) method is like this.
void addAll(Machine[] machines){
for(Machine m:machines){
add(m);
}
}
Your findAll(String[] names) method is like this.
Machine[] findAll(String[] names){
ArrayList<Machine> machines =new ArrayList<ArrayList>();
for(String s:names){
Machine m = find(s);
if(m!=null){
machines.add(m);
}
}
return machines.toArray(new Machine[0])
}

You could create a method like
void addAll(Machine[] machines)
and in its implementation, you add all elements from this array into the hashtable.

add methods
void add(Machine[] arr);
Machine[] find(String[] names);
and implement them in your class

Since you asked to this with an array i have tried it with the arrays. But I would rather suggest to go with an ArrayList as it is dynamic and insertion and searching is also fast and easy. Never mind try the following snippet.
class Machine
{
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
Machine() { name = null; }
}
interface Att
{
void add(Machine obj);
Machine find(String name);
}
//MachineAtt class
class MachineAtt implements Att
{
protected Machine[] arr = new Machine[10];
#Override
public void add(Machine obj) {
for(int i = 0; i<arr.length;i++ )
{
if(arr[i]==null)
arr[i] = obj;
}
}
#Override
public Machine find(String name) {
Machine mac = null;
for(int i = 0;i<arr.length;i++)
{
if(arr[i].getName().equals(name))
mac = arr[i];
}
return mac;
}
}
public class TEst {
public static void main(String[] args) {
Machine car = new Machine();
car.setName("MB");
//create an object of MachineAtt
MachineAtt foundit = new MachineAtt();
foundit.add(car);
foundit.find("MB");
}
}

Related

Java Objects in Array List

i would like to run the update function automatically for every object i create. What do I have to change in my code, unfortunately it doesn't work
How can I initialize an object in my ArrayList?
:(
Creating an Arraylist and initialize with name
public class Main {
public static void main(String... args) {
Zuhoerer Maria = new Zuhoerer("Maria");
Zuhoerer Sepp = new Zuhoerer("Sepp");
Zeitansager.sagAn();
}
}
class Zuhoerer {
private String name;
private String Ansager;
Zuhoerer(String name) {
this.name = name;
}
private void setAnsager(String datumstring) {
Ansager = datumstring;
}
void update() {
setAnsager(Zeitansager.getZeit());
Zeitansager.schreibeEin(name);
System.out.println(name + " hat gerade die die Zeitansage gehört:
[Datum/Uhrzeit]: " + Ansager);
Zeitansager.trageAus(name);
}
}
class Zeitansager {
private static String datumString;
private static ArrayList<String> abonnenten;
Zeitansager(String datumString) {
Zeitansager.datumString = datumString;
abonnenten = new ArrayList<>();
}
static void schreibeEin(String name) {
abonnenten.add(name);
}
static void trageAus(String name) {
abonnenten.remove(name);
}
static void sagAn() {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY' 'HH:mm:ss");
String datum = sdf.format(new Date());
datumString = datum;
for (int i=1; i <= abonnenten.size(); i++) {
abonnenten.update();
}
}
static String getZeit() {
return datumString;
}
}
update function is not called
Your ArrayList in Zeitansager have to be of type Zuhoerer rather than String.
Then in your loop in sagAn() you need to invoke:
abonnenten.get(i).update();
instead of:
abonnenten.update();
Finally your method static void schreibeEin(String name), should actually take a Zuhoerer as an argument.
To run "update" function every time you create an object you must put a call to this function inside your constructor. Like this:
Zuhoerer(String name) {
this.name = name;
update();
}
What are you trying to do with your arraylist? Give me more details so I can try to help you.

Arraylist not adding java

I am doing a simple sch program to add friends, which is to add objects into an arraylist. I followed everything but my method befriend() doesn't seem to work.
When i manually test using the .add() in the main, it works. Where am i doing wrongly?
import java.util.*;
public class NetworkFriends {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Person me = new Person("Aloysius", 1);
ArrayList<Person> myList = new ArrayList<Person>(Arrays.asList(me.getFriendList()));
Person p1 = new Person("Gorgon", 2);
Person p2 = new Person("Eddy", 3);
me.befriend(p1);
for(Person i : myList) {
System.out.println("Name: " + i.getName());
}
}
}
class Person
{
private int id;
private String name;
private ArrayList<Person> friendList;
private static int runningNum = 0;
private static int friendsLimit = 5;
private String degree;
private int degreeNum;
/* Constructor - 1 param */
public Person(String name, int degreeNum)
{
//Implement your code here..
//Initialize all necessary variable(s)
this.name = name;
friendList = new ArrayList<Person>(5);
this.degree = degree;
this.degreeNum = degreeNum;
}
public void befriend(Person p){
//Implement your code here..
ArrayList<Person> anotherList = new ArrayList<Person>(Arrays.asList(p.getFriendList()));
for(Person i : friendList) {
if(!isFriend(this) && friendList.size() < 5) {
friendList.add(p);
anotherList.add(this);
}
else if(!isFriend(this) && friendList.size() == 5) {
System.out.println("Friends limit reached");
}
else {
System.out.println("Already in friend list");
}
}
}
}
public boolean isFriend(Person p){
//Implement your code here..
boolean isItAFriend = true;
for(Person i : friendList) {
if(friendList.contains(p)) {
isItAFriend = true;
}
else {
isItAFriend = false;
}
}
return isItAFriend;
}
The problem is with the foreach loop in your befriend method. You are creating a new Person with the constructor that creates a empty friend list with an initial size of 5, but is still empty.
In your befriend method, you then are looping for each friend in this empty list. So the code within the loop will not be executed and the friend is never added to a list.
I suspect you want to do something like this: (and as this looks like homework I will only give you pseudo-code)
Is the person already a friend
Yes - nothing needs to be done or give feedback and return
No - Continue
Have they reached their friend limit
Yes - display feedback and return
No - Continue
Add the friend

Java programming error Pass by reference

I have an java application where a object reference "Validate.Options" is passed as parameter to the function "ValidateResult(Validate.Options option)" and the function is called iterative. Within this function based on the certain condition the property "enableProcessing" of the passed object gets changed which does not get reset on the next iterate. How can I reset this property?
Below is the sample code.
public interface Validate
{
public List validate();
public class Options implements Serializable
{
public String name;
public boolean enableProcessing = true;
public Options(String name)
{
this.name = name;
}
}
}
public class Coder
{
public String name;
public int age;
public Coder(String name, int age)
{
this.name = name;
this.age = age;
}
public void ValidateResult(Validate.Options option)
{
if(option.name.equals(this.name) && option.enableProcessing)
{
option.enableProcessing = false;
//
//business logic and function call
//
}
}
public static void main(String[] args)
{
Validate.Options options = new Validate.Options("Test");
List<Coder> coders = new ArrayList<Coder>();
Coder coder = new Coder("Test", 28);
Coder coder1 = new Coder("XYZ", 18);
Coder coder2 = new Coder("Test", 16);
coders.add(coder);
coders.add(coder1);
coders.add(coder2);
for(Coder co : coders)
{
co.ValidateResult(options);
}
}
}
If I understood the question well - in your for loop, simply add a line of code to reset the value of your public Validate.Options.enableProcessing field
for(Coder co : coders)
{
//reset options object for the next iteration
options.enableProcessing = true;
co.ValidateResult(options);
}
Make options immutable if you do not want it to be changed:
public class Options implements Serializable
{
public final String name; // final prevents changes
public final boolean enableProcessing = true; // final prevents changes
public Options(String name)
{
this.name = name;
}
}
To locally work with enableProcessing copy its value to a local variable.
public void ValidateResult(Validate.Options option)
{
boolean enableProcessing = option.enableProcessing; // create local copy
if(option.name.equals(this.name) && enableProcessing) // use local copy
{
enableProcessing = false; // only change local copy
//
//business logic and function call
//
}
}
Alternatively create new, fresh Options for each loop:
public static void main(String[] args)
{
List<Coder> coders = Arrays. asList(
new Coder("Test", 28),
new Coder("XYZ", 18),
new Coder("Test", 16)
);
for(Coder co : coders)
{
Validate.Options options = new Validate.Options("Test"); // fresh options for each iteration
co.ValidateResult(options);
}
}

How do I sort an array of objects of different class types?

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

Calling a get name method for an object returns null

I have a method that goes through each element in the ArrayList 'Clearance' and if it is an instance of HighClearance I want to add it to a String list of names.
Problem: Whenever I call the getName() method which is in the 'Clearance' superclass, it just returns null and dosent return the name.
public static String peopleClearance (ArrayList<Clearance> clearances) {
String names = "";
for(Clearance c: clearances) {
if(c instanceof HighClearance) {
System.out.println(c.getName()); //tested using sysout statement, just prints ''
names += c.getName();
}
}
return names;
}
In the main method:
Note: The constructor in the Clearance class: public Clearance(String pname)
ArrayList<Clearance> clear= new ArrayList<Clearance>();
clear.add(new HighClearance("Mike"));
clear.add(new HighClearance("John"));
System.out.println(peopleClearance(clear));
Please check with this working example if your superclass/subclass is using the name property right:
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<Clearance> clearances = new ArrayList<>();
clearances.add(new Clearance("C-Tes"));
clearances.add(new HighClearance("H-Test"));
clearances.add(new Clearance("CC-Test"));
clearances.add(new HighClearance("HH-Test"));
System.out.println(peopleClearance(clearances));
}
// changed the parameter to List interface instead of ArrayList
public static String peopleClearance(List<Clearance> clearances) {
String names = "";
for (Clearance c : clearances) {
if (c instanceof HighClearance) {
System.out.println(c.getName()); // tested using sysout statement, just prints ''
names += c.getName();
}
}
return names;
}
}
class Clearance {
private String name;
public Clearance(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
}
class HighClearance extends Clearance {
// if required!
public HighClearance(String name) {
super(name);
}
}

Categories

Resources