I have simply this below class structure and I want to add any item to it.
public class Person implements Serializable {
private String name;
private String mobile;
public Person(String n, String e) { name = n; mobile = e; }
public String getName() { return name; }
public String getMobile() { return mobile; }
#Override
public String toString() { return name; }
}
I want to add any item like with this:
people = new Person[]{
new Person("Hi" , " programmer"),
new Person("Hello", " world")
};
My code is this and I want to add items into that by while() my code is don't correct.
people = new Person[]{};
while (phones.moveToNext())
{
people = new Person("Hi" , " programmer");
people = new Person("Hello", " world")
}
you have error in your source code you are trying to put Object of person into array so it will gives you compilation error
to overcome this problem first take List of Type Person and convert it into array and do your business logic on Array its better to use List instead of Array
List<Person> personlst = new ArrayList<Person>();
while (phones.moveToNext())
{
personlst.add(new Person("Hi" , " programmer"));
personlst.add(new Person("Hello", " world"));
}
Object[]arryPer = personlst.toArray();
Person[]people = new Person[arryPer.length];
for (int j = 0; j < arryPer.length; j++) {
people[j] = (Person) arryPer[j];
}
above code of block give you array of type people
You are not defining the number of elements that you want to push into array. Also you are not even making those elements to an array. You should do something like:
int i =0;
people = new Person[1000];// you need to define how many elements you need here or go for list
while (phones.moveToNext())
{
people[i++] = new Person("Hi" , " programmer");
people[i++] = new Person("Hello", " world")
}
Define first the size of your Person.
Person[] people = new Person[10];
then do your iteration for example.
for(int i = 0; i < 0; i++){
people[i] = new Person("Hi" , " programmer");
}
first put all elements in list then form the array:
List<Person> list = new ArrayList<Person>();
while (phones.moveToNext()) {
list.add(new Person("Hi", " programmer"));
list.add(new Person("Hello", " world"));
}
Person[] persons = new Person[list.size()];
list.toArray(persons);
}
Try Arrays.asList
http://www.tutorialspoint.com/java/util/arrays_aslist.html
Note - it is good only for a small number of elements as arrays generally take contiguous memory.
As people have stated above, list is any day better from space point of view.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i have multiple arraylist like this:
arraylist
arrayList.add(product1);
arrayList.add(product2);
arrayList.add(product3);
arrayList.add(product4);
.
.
.
.
arrayList.add(productn);
arraylist2
arrayList2.add(name1);
arrayList2.add(name2);
arrayList2.add(name3);
arrayList2.add(name4);
.
.
.
arrayList2.add(namen);
arraylist3
arrayList3.add(id1);
arrayList3.add(id2);
arrayList3.add(id3);
arrayList3.add(id4);
.
.
.
arrayList3.add(idn);
i want to create string of array combine of arraylists above
with index of string in arraylist
so something like this
string[1] = {product1,name1,id1 }
string[2] = {product2,name2,id2 }
.
.
.
string[n] = {productn,namen,idn }
any idea how to do it?
sorry before
and thanks in advance
Make a class and then an array of instances/objects of that class. Here's an example,
public class Product{
String name;
String id;
public Product(String name, String id){ //constructor for the object
this.name = name;
this.id = id;
}
}
Then in your main method, create an array of type Product and added instances of Product to the array,
Product[] products = new Product[10];
products[0] = new Product("cheese", "0");
System.out.println(products[0].name + " " + products[0].id);
You can adjust to your liking, for example you can edit the Product class by adding more instance fields other than name and id, resize the array, change the array to an arraylist, etc..
Do you mean something like that?
int size = 10;
List<String> arr1 = new ArrayList<>();
List<String> arr2 = new ArrayList<>();
List<String> arr3 = new ArrayList<>();
String[] string = new String[size];
for (int i = 0; i < size; i++) {
string[i] = arr1.get(i) + arr2.get(i) + arr3.get(i);
}
You can loop through them in one loop and create an object with it.
we need to create a class
// The data type will change based on the data type you have them as
public class MyObject {
private Product product;
private Name name;
private Id id;
public MyObject(Product p, Name n, Id i) {
product = p;
name = n;
id = i;
}
// All Getters & toString()
}
Now for the loop :
List< MyObject> myList = new ArrayList < MyObject >();
for ( int i=0 ; i < arrayList || i < arrayList2 || i < arrayList3 ) {
myList.add(new MyObject(arrayList.get(i),arrayList2.get(i),arrayList3.get(i)))
}
Note you can override the toString method in you class to get the output in the way you want.
EG:
public String toString() {
return "Name: '" + this.name + "', ID: '" + this.id + "', Product: '" + this.product + "'";
}
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
arrayList.add("product1");
arrayList.add("product2");
arrayList.add("product3");
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("name1");
arrayList2.add("name2");
arrayList2.add("name3");
List<String> arrayList3 = new ArrayList<>();
arrayList3.add("id1");
arrayList3.add("id2");
arrayList3.add("id3");
int n = arrayList.size();
List<String[]> productlist = new ArrayList<>();
for(int i = 0; i< n;i++){
productlist.add(new String[]{arrayList.get(i),arrayList2.get(i),arrayList3.get(i)});
System.out.println(Arrays.toString(productlist.get(i)));
}
}
I was trying to take in a user ID and check for it against a list to see if it exists already. If it does, then print "ID already exists" if not, then take in the user name and store it in the list.
private LinkedList<Person> people = new LinkedList<Person>();
private void addPerson(){
int personId = readPersonId();
Person person = person(personId);
if (person.hasId){
System.out.println("ID already exists");
}
else{
String s = readName();
people.add(new Person(personId, s, 2));
}
}
However my program stops in the first loop for some reason.
You can dump your arraylist into a set and than compare these 2. If the size of the set is lower than arraylist size, then there are duplicates.
ArrayList<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);
if(set.size() < list.size()){
/* There are duplicates in your arrayList */
}
go through the list of people you have already and look for anyone with the same id. if there are no matching ones, the go a head and add the new person to the list.
private LinkedList<Person> people = new LinkedList<Person>();
private void addPerson(){
int personId = readPersonId();
boolean found = false;
for (Person curr : people) {
if (curr.getId() == personId){
System.out.println("ID already exists");
found = true;
break;
}
}
if (!found) {
Person person = person(personId);
String s = readName();
people.add(person);
}
}
I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.
EDIT: As requested
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:
ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;
Does not look great to me :-(
In your specific case, al is an ArrayList<String>. That means al.get(...) returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayList and add your single string to it and return that.
Your declared return type needs to match the object you are returning. So for example:
ArrayList<String> al = ...;
String getSingleItem (int index) {
return al.get(index);
}
ArrayList<String> getSingleItemAsArrayList (int index) {
ArrayList<String> single = new ArrayList<String>();
single.add(al.get(index));
return single;
}
ArrayList<String> getItems () {
return al;
}
By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.
Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.
EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.
//ADDING AND deleting employees
//Displaying employee list
public class EployeeDB {
static ArrayList e = new ArrayList<>();
public static boolean addEmployee(Employee e1) {
e.add(e1);
System.out.println("Employee added");
return true;
}
public static boolean deleteEmployee(int ecode) {
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
e.remove(i);
break;
}
}
if (temp == 1)
System.out.println("Emp deleted");
else
System.out.println("Deletion unsuccessful, check ecode again");
return true;
}
public static String showPaySlip(int ecode) {
double salary = 0;
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
salary = e.get(i).getSalary();
break;
}
}
if (temp == 1)
return "Salary is" + salary;
else
return "No employye found with the specified ecode";
}
public static ArrayList<Employee> listAll() {
return e;
}
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setID(20);
e1.setName("sai");
e1.setSalary(150.00);
addEmployee(e1);
Employee e2 = new Employee();
e2.setID(30);
e2.setName("kumar");
e2.setSalary(1500.00);
addEmployee(e2);
deleteEmployee(30);
System.out.println(showPaySlip(30));
for (int i = 0; i < e.size(); i++)
System.out.println(
listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());
}
}
i have list array of type Car , but in for loop i set to it some variable strings
but after finished looping i found the last element of list is overwrite all previous elements
Car testset = new Car();
private void populateRandomCars(List<Car> list, int size,
List<Integer> teachers, List<String> state){
try {
for (int i = 0; i < size; i++)
list.add(testset.add(getRandomColor(teachers.get(i)),
getRandomYear(state.get(i))
));
car class :
private String teachers;
private String state;
public Car add(String teachers,String state) {
this.teachers=teachers;
this.state=state;
return Car.this;
}
If you just want to add Car objects in the list. Your for loop should instantiate a new Car object each time.
Car testset = null;
try {
for (int i = 0; i < size; i++) {
testset = new Car();
list.add(testset.add(getRandomColor(teachers.get(i)), getRandomYear(state.get(i))));
// Additional code goes here.
} catch (Exception ex) {
// Exception handling
}
Firstly, it seems that your question is incomplete.
Secondly, to fix up your code, just add the
Car car = new Car();// testset->car
inside the populateRandomCars method.
Then it will create and add a new Car.
I ran into a bind whereby I had to sort the data read from the phones PIM. In doing this I lost the other to which each contact field was referenced to the telephone number because I made use of 2 separate vectors as illustrated below
Before sorting
Nna - +445535533
Ex - +373773737
Ab - +234575757
After sorting.(Which shouldn't be)
Ab - +445535533
Ex - +373773737
Nna - +234575757
This gives an undesired behavior since the sort removes the index to index pointer of the vectors and a selected name (in a Multiple list Box) will get a wrong number.
Alternatively,
I used a hashtable, with the intention of using the names as keys and numbers as the values.
But this pairing means duplicate names being used as keys will not be allowed. Thus I made it a i.e the phone number as keys instead.
I don't want to sound like a cry baby so I stop here for a while and so you the code with a hope u guys would understand it
MY QUESTION
1. Is there a better way/algorithm to implement this?
2. How do I implement the getSelectedItems() in such a ways that it grabs the numbers of the selected indexes of a MULTIPLE CHOICE LIST from a hashTable
import java.util.Enumeration;
import java.util.Vector;
import java.util.Hashtable;
import javax.microedition.lcdui.List;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;
/**
*
* #author nnanna
*/
public class LoadContacts implements Operation {
private boolean available;
private Vector telNames = new Vector();
Vector telNumbers = new Vector();
Hashtable Listcontact = new Hashtable();
private String[] names;
public Vector getTelNames() {
return telNames;
}
public Hashtable getListcontact() {
return Listcontact;
}
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute()");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME) && contactList.isSupportedField(Contact.TEL)) {
Enumeration items = contactList.items();
Hashtable temp = new Hashtable();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone availableContacts
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
Listcontact.put(telNumber, contactName);
temp.put(contactName, telNumber);
}
names = getSortedList();
// Listcontact = temp;
System.out.println(temp + "-------");
System.out.println(Listcontact + "*******");
shortenName(contactName, 20);
}
available = true;
}
} else {
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}
private void shortenName(String name, int length) {
if (name.length() > length) {
name = name.substring(0, 17) + "...";
}
}
public Vector getSelectedItems(List lbx) {
boolean[] arrSel = new boolean[lbx.size()];
Vector selectedNumbers = new Vector();
int selected = lbx.getSelectedFlags(arrSel);
String selectedString;
String result = "";
for (int i = 0; i < arrSel.length; i++) {
if (arrSel[i]) {
selectedString = lbx.getString(lbx.getSelectedFlags(arrSel));
result = result + " " + i;
System.out.println(Listcontact.get(selectedString));
// System.out.println(telNumbers.elementAt(i));
}
}
return selectedNumbers;
}
private String[] sortResults(String data[]) {
RecordSorter sorter = new RecordSorter();
boolean changed = true;
while (changed) {
changed = false;
for (int j = 0; j < (data.length - 1); j++) {
String a = data[j], b = data[j + 1];
if (a != null && b != null) {
int order = sorter.compare(a.getBytes(), b.getBytes());
if (order == RecordSorter.FOLLOWS) {
changed = true;
data[j] = b;
data[j + 1] = a;
}
}
}
}
return data;
}
public String[] getNames() {
return names;
}
Vector elements = new Vector();
private String[] getValueArray(Hashtable value) {
System.out.println(Listcontact + " c");
Enumeration e = value.elements();
while (e.hasMoreElements()) {
elements.addElement(e.nextElement());
}
String[] elementsArray = new String[elements.size()];
elements.copyInto(elementsArray);
elements.removeAllElements();
System.out.println(elementsArray + " k");
return elementsArray;
}
public void getDuplicates(Vector realValue) {
Vector duplicate = new Vector();
Enumeration e = realValue.elements();
for (int i = 0; e.hasMoreElements(); i++) {
if (duplicate.isEmpty() || !duplicate.elementAt(i).equals(e.nextElement())) {
break;
} else {
duplicate.addElement(e.nextElement());
}
}
}
public String[] getSortedList() {
return sortResults(getValueArray(Listcontact));
}
}
Let me reiterate you requirement: You want a method that will sort the contacts read from native phonebook, then alphabetically sort them on name.
Following is the approach,
Replace the vectors and hash-tables in your code with a single vector, say contactListVector, containing elements of type ContactItem, don't worry this class is explained below. Fundamentally the contact's name and number(s) are linked together in a ContactItem, hence you do not have to worry about there mappings which reduces the usage of redundant data structures.
class ContactItem {
private String name;
private String tnumber; //this can also be a data structure
//for storing multiple numbers
ContactItem( String name, String tnumber) {
this.name = name;
this.tnumber = tnumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTnumber() {
return tnumber;
}
public void setTnumber(String tnumber) {
this.tnumber = tnumber;
}
}
You can reuse the sorting algorithm on contactListVector by comparing the member variable ContactItem.name of the vector element. Also you can deploy different sorts on member variables numbers and/or names. Also there are lots of libraries for JavaME available that have better sorting algorithm's implemented if need be use them.
I would recommend you to perform the sorting once on the contactListVector elements at the end of your method loadNames(...) maybe in the finally block triggered by some boolean variable. The current sorting call in each iteration on items enumeration is expensive and time consuming.
Also you can serialize / deserialize the ContactItem thus persist your contact list.
Let me know if you need detailed explanation.
What about inserting the contact name and numbers inside a recordStore , so you can later make a sort by creating a class which implements RecordComparator.
This statement in your code makes no sense:
selectedString = lbx.getString(lbx.getSelectedFlags(arrSel))
Per lcdui List API documentation above will return the string located at the index equal to the number of selected elements why would you need that?
If you need to output selected text for debugging purposes, use lbx.getString(i) instead.
To implement the getSelectedItems() in such a ways that it grabs the numbers of the selected indexes of a MULTIPLE CHOICE LIST do about as follows:
public Vector getSelectedItems(List lbx) {
boolean[] arrSel = new boolean[lbx.size()];
Vector selectedNumbers = new Vector();
int selected = lbx.getSelectedFlags(arrSel);
System.out.println("selected: [" + selected + "] elements in list");
String selectedString;
String result = "";
for (int i = 0; i < arrSel.length; i++) {
if (arrSel[i]) {
// here, i is the selected index
selectedNumbers.addElement(new Integer(i)); // add i to result
String selectedString = lbx.getString(i);
System.out.println("selected [" + selectedString
+ "] text at index: [" + i + "]");
}
}
return selectedNumbers;
}
As for sorting needs, just drop the HashTable and use Vector of properly designed objects instead as suggested in another answer - with your own sorting algorithm or one from some 3rd party J2ME library.
I would suggest you to have Contact class with name and Vector of numbers. And instead of sorting names array sort the array of contacts.