Java - clone class based on array - java

I have a class called NewClass, and inside this class I have another class called people. I want to make clones of the people class, and have them with different values and names; however, I want these classes named based on a String array.
Lets say I have a String array with 5 words:
String[] array = new String[] { "first", "second", "third", "fourth", "fifth" };
And I have a class with a few variables like:
class people
{
String name;
int id;
}
Is it possible to clone or create a new class, using "people" as the model with the Strings from array? I've tried this so far and it doesn't work:
for (int i = 0; i < array.length; i++)
{
people array[i] = new people();
}
Also, how would these classes be accessed from outside the "NewClass"; would it be possible to access like this:
class OtherClass
{
NewClass myclass = new NewClass();
System.out.println(myclass.first.name);
}

You really should read a Java tutorial.
Your code is wrong at so many levels (starting with not following Java naming conventions, and improperly using the technical term clone for transforming an array of strings into an array of other objects), its hard to give you a concise answer.
Really, read a Java tutorial. They'll tell you how to make an People[] array. Or even better: an ArrayList<People>.
From reading a well-written tutorial or book you will learn much more than from the short answers you can expect to get here. See: the tutorials and books are often written by people who teach professionally...

You cannot dynamically set variable names based on Strings. You've already shown us a better example- creating an array of 'people' class and filling it with 'people' objects (Java best practices suggests using a capital at the start of class names though). You can easily set the 'name' field of the 'people' class in the same loop you used to instantiate all the 'people' objects by iterating through the String array. Then it is as simple as knowing the index of the 'people' object you want to retrieve.
peopleArray = new people[array.length];
for (int i = 0; i < array.length; i++)
{
peopleArray[i] = new people();
peopleArray[i].name = array[i];
}
Then just:
System.out.println(peopleArray[index].name);
You can simplify it by writing a constructor for the 'people' class

I'm not sure what exactly you are trying to do. But if you really want to dynamically set variable names based on Strings you need a HashMap.
Here is an example.
import java.util.HashMap;
class Person {
private String name;
private int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
#Override
public String toString() {
return "Person - name = " + name + ", id = " + id;
}
}
public class MyClass {
private static HashMap<String, Person> people = new HashMap<>();
public static void main(String[] args) {
String[] keys = { "first", "second", "third", "fourth", "fifth"};
String[] names = { "Emily", "Bob", "Susan", "Bill", "Alice"};
int[] ids = {1, 2, 3, 4,5};
for(int i = 0; i < keys.length; i++) {
Person p = new Person(names[i], ids[i]);
people.put(keys[i], p);
}
System.out.println(people.get("first"));
System.out.println(people.get("second"));
}
}
But I doubt that you actually need to do this. Maybe all you want to do is set the name of the person to a string from the array. In which case you don't need the HashMap.

Related

Refining data in java array

Ok, I have reworked the question. I was wondering what the best way to refine an array of objects would be.
I have an array of objects. These objects will be referred to as objectA and this can be seen below:
public class objectA {
private String ID;
private String groupID;
private String isEligable;
public String getID()
{
return ID;
}
public void setID(String ID)
{
this.ID = ID;
}
public String getgroupID()
{
return groupID;
}
public void setgroupID(String groupID)
{
this.groupID = groupID;
}
public String getIsEligable()
{
return isEligable;
}
public void setIsEligable(String isEligable)
{
this.isEligable = isEligable;
}
}
As you can see the object has an ID, groupID and an isEligable variable. These objects will be added to an array and there can only ever be a maximum of two objects which have the same groupID. One where isEligable = "F" and one where isEligable = "T". What I want to do is efficiently refine the array so that the group which has 2 objects associated to it only displays the object which isEligable = "T", ie, disregard the object in the same group where isEligable = "F". So in the below example only object 1 and 3 would be in the array:
Public class testExample
{
objectA[] objectArray = new objectA[3]
objectA object1 = new objectA();
object1.setID = "1"
object1.setGroupID = "0001"
object1.setIsEligable = "F"
objectA object2 = new objectA();
object2.setID = "2"
object2.setGroupID = "0002"
object2.setIsEligable = "F"
objectA object3 = new objectA();
object3.setID = "3"
object3.setGroupID = "0002"
object3.setIsEligable = "T"
objectArray[0] = object1;
objectArray[1] = object2;
objectArray[2] = object3;
}
I am assuming I need to sort them into a group somehow then loop round each group to determine which one (if any) where isEligable = "T" and if so add that to a new array else if none meet that criteria in the group just add the one where isEligable ="F" to the array.
My issue is though that I dont know how big the new array should be. I suppose this is where I should use an array list? though I wanted to avoid this if possible but I suppose in this case an array list makes the most sense. I also think this seems quite costly in terms of performance?
Any opinions, help or guidance would be greatly appreciated.
Thanks.

Associative arrays in Java

I'm from a PHP background, and I'm trying to create a multidimentional array with a difficulty in understanding the Java way of doing things. I thought this could be achieved using JSON and the GSON library, but I'm failing to understand how this is done having followed several tutorials online.
Here is what I'm after in PHP, how can I achieve the same thing in Java?
function creatCars($id) {
$aCars = array(
0 => array(
'name' => 'vauxhall',
'doors' => 5,
'color' => 'black',
),
1 => array(
'name' => 'peogeot',
'doors' => 3,
'color' => 'red',
),
);
return $aCars[$id];
}
function printFirstCarName($sName) {
$aCar = createCars(0);
echo $aCars['name'];
}
//prints "vauxhall"
printFirstCarName();
Arrays in PHP are not the same as arrays in Java. Here are the differences:
PHP:
PHP arrays are actually dictionaries. They store a value for each key, where a key can be an integer or a string. If you try to use something else as a key, it will be converted to either an integer or a string.
Java:
Arrays in Java
Java arrays are not associative in the same way as they are in PHP. Let's start with one-dimensional arrays in Java:
A one-dimensional array in Java has a fixed length (that cannot be changed) and each key is an integer in the range of 0 to array.length - 1. So keys, actually called indexes, are always integers. Also, in Java, if you have an array with the keys 2 and 4, you also have (at least) the keys 0, 1 and 3, because the length has to be at least 5 then.
Arrays in Java also have exactly one type and each values in the array can only be of the specified type. Neither size nor type of an array can be changed.
When you create an array in Java, you have two possibilities:
explicitly specify the length when creating the array
String[] words = new String[4];
The variable words now holds an array of type String with the length a length of 4. The values of all indexes (0 to 3) are initially set to null.
specify elements when creating the array
String[] words = new String[] {"apple", "banana", "cranberry"};
The variable words now holds an array of type String with a length of 3. The elements contained are as specified with the first element bound to index 0, the second element bound to index 1, and so on.
You can think of multi-dimensional arrays as of an array which holds arrays. A 2-dimensional array could look like this:
String[][] twoD = new String[][] {
{"apple", "banana", "cranberry"},
{"car", "ship", "bicycle"}
}
For this twoD[0][2] would be "cranberry" and twoD[1][1] would be "ship". But the number of dimensions of an array does not influence the fact that the keys are integers.
Maps in Java:
Even though Java has no built-in language construct for associative arrays, it offers the interface Map with various implementations, e.g. HashMap. A Map has a type of which the keys are, and a type of which the values are. You can use maps like this:
HashMap<String, String> map = new HashMap<String, String>();
map.put("car", "drive");
map.put("boat", "swim");
System.out.println("You can " + map.get("car") + " a car.");
System.out.println("And a boat can " + map.get("boat") + ".");
This will output:
You can drive a car.
And a boat can swim.
The answer:
The one-to-one way in Java
The answer to your question is that it is not really possible in a reasonable way becasue some of your values are strings, and some are integers. But this would be the most similar code to your PHP array:
//array of HashMaps which have Strings as key and value types
HashMap<String, String>[] cars = new HashMap<String, String>[2];
HashMap<String, String> first = new HashMap<String, String>();
first.put("name", "vauxhall");
first.put("doors", "5");
first.put("color", "black");
HashMap<String, String> second = new HashMap<String, String>();
second.put("name", "peogeot");
second.put("doors", "3");
second.put("color", "red");
//put those two maps into the array of maps
cars[0] = first;
cars[1] = second;
This solution is not very handy, but it is the way that comes closest to your given datastructure.
The cuter way in Java
It seems however, that each of the entries in your PHP array has exactly three properties: name, doors and color. In this case, you may want to create a class Car with these member variables, and store them in an array. This would look like this:
public class Car {
//member variables
public String name;
public int doors;
public String color;
//constructor
public Car(String name, int doors, String color) {
this.name = name;
this.doors = doors;
this.color = color;
}
}
Now, when you have the class Car, you can create an array of all your cars like this:
Car[] cars = new Car[2];
cars[0] = new Car("vauxhall", 5, "black");
cars[1] = new Car("peogeot", 3, "red");
This is the nicer way to do this in Java.
Instead of creating 2D Array you can create 1 class Car
public class Car{
private String carName;
private String color;
private int noOfDoors;
public car(String carName,int door,String color){
this.carName=carName;
this.door=door;
this.color=color;
}
public String getCarName(){
return getCarName;
}
public void setCarName(String carName){
this.carName=carName;
}
// Same getters(getXXX) and setters(setXXX) for other Variables
}
Now create Objects of above class
Car audi=new Car("audi",2,"Black");
Car bmw=new Car("bmw",4,"White");
Now add these to the List<Cars>
List<Car> listOfCars=new ArrayList<Car>();
listOfCars.add(audi);
listOfCars.add(bmw);
Now to Print First Car Name
Car firstCar=listOfCars.get(0);
System.out.println(firstCar.getCarName()); //here getter Method Helped you
I would suggest to get familiar with HashMaps, Maps and ArrayLists. In Java and many other languages is something analogous to a video game cheat.
private static Map<Integer, HashMap<String, String> > carMap = new HashMap<Integer, HashMap<String, String> >();
But in this case you have to understand how would OO principles help you. You can create a class with Car objects and populate a HashMap etc.
class Car {
private String name, colour;....
public Car(){....}
public void setValues(...){....}
}
To achieve better what you want to I would suggest reading this and getting familiar with some design patterns. It's a bit further down the road, but do it for the lulz and seeing what it's out there. Example : http://howtodoinjava.com/2012/10/23/implementing-factory-design-pattern-in-java/
When moving from scripting to strongly typed languages sometimes you have to change your way of thinking too.
Firstly you should create class Car i.e:
public class Car {
enum ColorType {
BLACK, RED;
}
private String name;
private int doors;
private ColorType color;
Car(String name, int doors, ColorType color) {
this.name = name;
this.doors = doors;
this.color = color;
}
public String getName() {
return name;
}
public int getDoors() {
return doors;
}
public ColorType getColor() {
return color;
}
}
And now you can use arrays but better for you will be use ArrayList:
List<Car> cars = new ArrayList<Car>();
cars.add(new Car("vauxhall", 5, BLACK));
cars.add(new Car("peogeot", 3, RED));
for (Car car : cars ) {
System.out.println("Car name is: " + car.getName());
}
It seems what you are trying to achive is an 'array of cars'. So instead of creating an array of arrays, I recommend to literally implement an 'array of cars'.
To do this, I would define the car first, possibly in a different file:
class Car {
//you can make these private and use 'get' and 'set' methods instead
public String name;
public String color;
public int doors;
public Car() {
name = "";
color = "";
doors = 0;
}
public Car(String name, String color, int doors) {
this.name = name;
this.color = color;
this.doors = doors;
}
}
You can use the car structure in an another module like this:
Car[] cars = new Car[100]; //create one hundred cars
cars[11].doors = 4; //make the 12th car's number of doors to 4
You can use more flexible data structures, like Vectors, List, Maps, etc... Search for Java collections, you will find tones of info.
Java is not a loosely typed language, you have to tell the compiler what each variable is going to be. And to store this kind of structured data in Java, you should first declare a class and instantiate objects of that class. Following is how you would achieve the same thing as your PHP code:
class Car {
private String name, color;
private int doors;
Car(String name, int doors, String color) {
this.name = name;
this.doors = doors;
this.color = color;
}
public String getName() {
return this.name;
}
}
public class CarMainClass {
public static void main(String[] args) {
Car[] aCars = new Car[2];
aCars[0] = new Car("vauxhall", 5, "black");
aCars[1] = new Car("peogeot", 3, "red");
System.out.println("First car name is: " + aCars[0].getName());
}
}
Compile using:
javac CarMainClass.java
Then run:
java CarMainClass
You will have to learn the basics of Java first to understand the above code.

Is there a way to give names to row and column of a 2D array in Java?

I google it before, the answer was no but I wonder if there is any possible way.
Is there a way to give names to row and column of a 2D array in Java?
No you can't. 2D array is just array of arrays. You'll need to have 2 other arrays with names for columns and rows
Probably you can use something different (another data structure like Map) if you need to.
More dimensional arrays are normally the approach to avoid classes. For example:
String[][] persons;
persons[0][1];
If you are confronted with such a code you should first make it more readable.
public static final int FIRSTNAME = 0;
public static final int LASTNAME = 1;
persons[0][FIRSTNAME];
persons[0][LASTNAME];
A better way to encapsulate the data structure is a class:
public class Person {
private String firstname;
private String lastname;
public String getFirstname(){
return firstname;
}
public String getLastname(){
return lastname;
}
}
Person[] persons;
person[0].getFirstname();
Or if you want the change to be as minimal as necesarry:
public class Person {
public static final int FIRSTNAME = 0;
public static final int LASTNAME = 1;
private String[] personData;
public String getFirstname(){
return personData[FIRSTNAME];
}
public String getLastname(){
return personData[LASTNAME];
}
}
Make your choice
It seems that your requirement is to identify the rows. For that instead of using arrays you can use Map which are formed by unique keys.
You can define like
Map<String,ArrayList<SomeObject>> map = new HashMap<String,ArrayList<SomeObject>>();
By this way, you can put a key which can work as a row identifier as it is unique and add an entire arrayList as its value
Forget about associative arrays.You are in Java now and go for advanced way :)For this Java provides maps.You need to use the maps.
Here is a example
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map<String ,Integer> m1 = new HashMap<String ,Integer>();
m1.put("name1", 8);
m1.put("name2", 31);
m1.put("name3", 12);
m1.put("name4", 14);
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
If you need more deeply,As you are saying
is there a way to give names to row and column of a 2D array in Java?
then need to store a datastructure against a key then it is possible.You may store a Map against a key and then you will call it a multimap which will look like this
Map<X, Map<Y,Z>> map1;

Print ArrayList

I have an ArrayList that contains Address objects.
How do I print the values of this ArrayList, meaning I am printing out the contents of the Array, in this case numbers.
I can only get it to print out the actual memory address of the array with this code:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i));
}
list.toString() is good enough.
The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.
Add toString() method to your address class then do
System.out.println(Arrays.toString(houseAddress));
From what I understand you are trying to print an ArrayList of arrays and one way to display that would be
System.out.println(Arrays.deepToString(list.toArray()));
since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object
solution
in your Address class override the toString() method like this
public class Address {
int addressNo ;
....
....
...
protected String toString(){
return Integer.toString(addressNo);
}
now when you call
houseAddress.get(i) in the `System.out.print()` method like this
System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called
You can simply give it as:
System.out.println("Address:" +houseAddress);
Your output will look like [address1, address2, address3]
This is because the class ArrayList or its superclass would have a toString() function overridden.
Hope this helps.
assium that you have a numbers list like that
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
if you print the list
//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
System.out.print(number);
}
//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));
//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));
//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);
Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?
If you have an ArrayList of arrays (e.g.
int[] arr = {1, 2, 3};
houseAddress.add(arr);
Then to print the array values you need to call Arrays.deepToString:
for (int i = 0; i < houseAddress.size(); i++) {
System.out.println(Arrays.deepToString(houseAddress.get(i)));
}
public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+" ");
}
}
I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:
System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));
Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:
With annonymous class:
houseAddress.forEach(new Consumer<String>() {
#Override
public void accept(String s) {
System.out.println(s);
}
});
lambda expression:
houseAddress.forEach(s -> System.out.println(s));
or by using method reference:
houseAddress.forEach(System.out::print);
This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.
Simplest way to print an ArrayList is by using toString
List<String> a=new ArrayList<>();
a.add("111");
a.add("112");
a.add("113");
System.out.println(a.toString());
Output
[111, 112, 113]
Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print((houseAddress.get(i)).toString());
}
This helped to me:
System.out.println(Arrays.toString(codeLangArray.toArray()));
public static void main(String[] args) {
List<Moyen> list = new ArrayList<Moyen>();
Moyen m1 = new Moyen();
m1.setCodification("c1");
m1.setCapacityManager("Avinash");
Moyen m2 = new Moyen();
m2.setCodification("c1");
m2.setCapacityManager("Avinash");
Moyen m3 = new Moyen();
m3.setCodification("c1");
m3.setCapacityManager("Avinash");
list.add(m1);
list.add(m2);
list.add(m3);
System.out.println(Arrays.toString(list.toArray()));
}
You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String
Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Note : You can even use an enhanced for loop for this as mentioned by me in another answer
if you make the #Override public String toString() as comments,
you will have the same results as you did.
But if you implement your toString() method, it will work.
public class PrintingComplexArrayList {
public static void main(String[] args) {
List houseAddress = new ArrayList();
insertAddress(houseAddress);
printMe1(houseAddress);
printMe2(houseAddress);
}
private static void insertAddress(List address)
{
address.add(new Address(1));
address.add(new Address(2));
address.add(new Address(3));
address.add(new Address(4));
}
private static void printMe1(List address)
{
for (int i=0; i<address.size(); i++)
System.out.println(address.get(i));
}
private static void printMe2(List address)
{
System.out.println(address);
}
}
class Address{
private int addr;
public Address(int i)
{
addr = i;
}
#Override public String toString()
{
Integer iAddr = new Integer (addr);
return iAddr.toString();
}
}
You can even use an enhanced for loop or an iterator like:
for (String name : houseAddress) {
System.out.println(name);
}
You can change it to whatever data type houseAddress is and it avoids unnecessary conversions
Make sure you have a getter in House address class and then use:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i)**.getAddress()**);
}
you can use print format if you just want to print the element on the console.
for(int i = 0; i < houseAddress.size(); i++) {
System.out.printf("%s", houseAddress.get(i));
}
Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i).toString());
}
A general example:
ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]
This is a simple code of add the value in ArrayList and print the ArrayList Value
public class Samim {
public static void main(String args[]) {
// Declare list
List<String> list = new ArrayList<>();
// Add value in list
list.add("First Value ArrayPosition=0");
list.add("Second Value ArrayPosition=1");
list.add("Third Value ArrayPosition=2");
list.add("Fourth Value ArrayPosition=3");
list.add("Fifth Value ArrayPosition=4");
list.add("Sixth Value ArrayPosition=5");
list.add("Seventh Value ArrayPosition=6");
String[] objects1 = list.toArray(new String[0]);
// Print Position Value
System.err.println(objects1[2]);
// Print All Value
for (String val : objects1) {
System.out.println(val);
}
}
}
JSON
An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.
Example using Google's Gson:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
...
public static void printJsonString(Object o) {
GsonBuilder gsonBuilder = new GsonBuilder();
/*
* Some options for GsonBuilder like setting dateformat or pretty printing
*/
Gson gson = gsonBuilder.create();
String json= gson.toJson(o);
System.out.println(json);
}
Add toString() method to your class
houseAddress.forEach(System.out::println);
Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object
changing the String datatype to the appropriate datatype or class object as desired.
ArrayList<String> teamRoster = new ArrayList<String>();
// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");
System.out.println("Current roster: ");
for (String playerName : teamRoster) {
System.out.println(playerName);
// if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}

creating names for linked lists while looping (Java)

I have implemented a simple linked list class and I would now like to use it in a loop. I am wondering how to best assign names to the list in each iteration of the loop.
Essentially I am looping over some integers, and I would like to just give each list the name of that integer, but I cannot say
List i = new List();
right ?
There probably is an easy way to do this, but I m not sure how, and would be grateful for
I think you're confusing the role of variables with the role of collections. From your question I gather that you want to create a list for each index in your loop, and you would like to later be able to access that list by its index:
ArrayList<LinkedList<String>> listOfLists = new ArrayList<LinkedList<String>>();
for(int i = 0; i < 10; i++)
{
LinkedList<String> list = new LinkedList();
listOfLists.add(list);
// do stuff to the list...
}
// access
LinkedList<String> thirdList = listOfLists.get(2); // index 2 = third entry
So you see, the LinkedLists are not named according to the value of i, but you can still access them by a given value of i.
First of all, if if not for learning purposes, it is highly recommended not to implement your own classes for stuff that is already implemented in libraries.
For Lists, you should check out the collection framework: http://docs.oracle.com/javase/tutorial/collections/
I am not sure what you mean by "the name of that integer".
I assume you want to create a List of elements that contain both an integer, and a String representing the name of the value that is hold in the integer.
If it is the case, the best way to do this probably is to create your own Object:
class NamedInteger {
private int value;
private String name;
public NamedInteger(int value, String name) {
this.value = value;
this.name = name;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
public void setValue(int value) {
this.value = value;
}
public void setName(String name) {
this.name = name;
}
}
The advantage of this method, is that later, if you want to add other information to your object, it is very easy to do so.
And then, just have a List of those objects....
public static void main(String[] args) {
List<NamedInteger> list = new LinkedList<NamedInteger>();
list.add(new NamedInteger(1, "Hello");
...
}

Categories