Android ArrayList: check an element exists of another ArrayList - java

I have two ArrayList.
private ArrayList<Friend> friendsList = new ArrayList<Friend>();
private ArrayList<Friend> myFriendsList = new ArrayList<Friend>();
First one contains all Friend of database. Second one contains only user Friend. In my search option(SearchManager) i've a ListView contains searched friends of friendsList. When i select a Friend of ListView, i want to check if the Friend exists in myFriendsList. I used following code
friendListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
handelListItemClick(adapter.getItem(position));
}
});
private void handelListItemClick(Friend friend) {
for(Friend fr: myFriendsList){
Log.v("Check User Name:", fr.getName());
}
if (myFriendsList.contains(friend)) {works with matched friend}
But it can't check the selected Friend in myFriendsList. In LogCat it show myFriendsList information. Thanks in advance.
Update
Here is my Friend class
public class Friend {
private String id, name, thumbnailUrl;
public Friend() {
}
public Friend(String name, String thumbnailUrl) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
}
public Friend(String name, String thumbnailUrl, String id) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
this.id = id;
}
public String getID(){
return id;
}
public void setID(String id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}

To be able to use methods to find and search like contains your custom class MUST implement correctly the hasCode and equals methods.
Here is the link about the implementing hasCode and here about implementing equals. It is Java Best Practises website that I like very much and from where I've learned about it.

equals() is used in most collections to determine if a collection contains a given element
hashCode() of this object is calculated and used to determine where to search for the object in the hash tables.
For more information on either of these topics visit oracle webiste or take a look here
If You could decide that two Friend objects are equal to each other if just their id's are equal.
So , In your Friend Class include
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Friend)) return false;
Friend friend = (Friend) o;
if (!id.equals(friend.id)) return false;
return true;
}
#Override
public int hashCode() {
return id.hashCode();
}
Now just do,
private void handelListItemClick(Friend friend) {
if (myFriendsList.contains(friend)) {works with matched friend}
}
Edit
You can take a look at this tutorial to learn more about the topic

Related

Using Strings from resources in List.

I'm new to Android and I'm having a problem using String variables from resources in my code. I tried a couple of solutions found on the internet and Android API Guides, but they didn't work in this specific case, could also be me not using them correctly.
To be more specific, I have a Master/Detail flow activity and I would like to use resource strings as item names for multilanguage purposes, but I have a problem with recovering actual strings.
The error I get is:
Cannot resolve method 'getString()'
Here is my code based on android studio dummy file
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
static {
String temp = getString(R.string.cat_n1);
addItem(new CatName("1", temp);
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public FieldCat(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}
You need to specify the resource. Try this,
getResources().getString(R.string.cat_n1);
getString(int resId): Return a localized string from the application's package's default string table.
getResources().getString(int id): Returns the string value associated with a particular resource ID. It will be stripped of any styled text information.
Try using it with a constructor passing the context and calling getstring on that
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
public Categories(Context ct)
{
String temp = ct.getString(R.string.abc_action_bar_home_description);
addItem(new CatName("1", temp));
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public CatName(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}

How to compare two maps in java which is having the objects in it

import java.util.*;
class Getter_Setter
{
int id;
String name;
public List<Getter_Setter> buckets;
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setGetter_Setter(List<Getter_Setter> buck)
{
this.buckets=buck;
}
}
class Getter_Setter2
{
int id;
String name;
public List<Getter_Setter> buckets;
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setGetter_Setter2(List<Getter_Setter> buck)
{
this.buckets=buck;
}
}
class Simple
{
HashMap<String,Getter_Setter> map=new HashMap<String,Getter_Setter>();
HashMap<String,Getter_Setter2> map_getter_setter2=new HashMap<String,Getter_Setter2>();
public static void main(String arg[])
{
List<Getter_Setter> temp=sum();
List<Getter_Setter2>temp=sum1();
}
public static List<Getter_Setter> sum()
{
List<Getter_Setter> list=new ArrayList<Getter_Setter>();
Getter_Setter get=new Getter_Setter();
get.setId(30);
get.setName("Hanish");
System.out.println(get.getId());
System.out.println(get.getName());
list.add(get);
map.put(get.getId(),get);
return list;
}
public static List<Getter_Setter> sum1()
{
List<Getter_Setter2> list=new ArrayList<Getter_Setter2>();
Getter_Setter2 get=new Getter_Setter2();
get.setId(301);
get.setName("Hanish1");
System.out.println(get.getId());
System.out.println(get.getName());
list.add(get);
map_getter_setter2.put(get.getId(),get);
return list;
}
}
how to compare the two map objects which is having some values in this case.if these mapss conatins huge data but id's are unique.There is two classes first one is getter_setter which is having the data in the map object and in the second class which is getter_setter2 which is having the whole data in the map_getter_Setter. I need a comparison on the basis of id and then whole data is going to be compared. How can i do this?
If I understand your question correctly, The main problem is having the fields like id and data are inside hashmap classes and thus making it somewhat not so straightforward to compare.
You can write custom comparator class, which first compares on id and then data inside map by iteration and finally gives out equal. for this refer this answerenter link description here
The other option is to use comparison chain.enter link description here which will help you to use multiple comparisons easily.

how to remove duplicate objects with same id's in a set

HashSet contains objects,I want to remove duplicates whose objects are having same id's
the following is the code..
Set<Employee> empSet=new HashSet<Employee>();
empSet.add(new Employee(1,"naresh"));
empSet.add(new Employee(2,"raj"));
empSet.add(new Employee(1,"nesh"));
empSet.add(new Employee(2,"rajes"));
//i saw in some blog that we can use hashCode equals method, but i don't how to use that in this context, please help me out
import groovy.transform.EqualsAndHashCode
#EqualsAndHashCode(includes='id')
class Employee {
int id
String name
}
You can remove constructors as well if #Canonical AST is used. Canonical also provides #EqualsAndHashCode, but to add the includes it has to be used separately again.
UPDATE
If the class is not modifiable and you have a list/hasSet then you can use unique with a closure to perform the uniqueness. Assuming the SolrDocument mentioned in comment is referred as Employee and you have the above HashSet with duplicate ids, then below should work:
empSet.unique { it.id } //this mutates the original list
empSet.unique( false ) { it.id } //this does not mutate the original list
Write equals and hashCode as shown below
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (id != employee.id) return false;
return true;
}
#Override
public int hashCode() {
return id;
}
}
You need to override equals() method in your Employee class and it will be taken care of. Set uses the equals method to compare the objects inserted in the Set.
public class Employee
{
public boolean equals(Employee e)
{
/// logic to compare 2 employee objects
}
}

Cannot bind RemoteObject from BlazeDS

I'm using BlazeDS in Tomcat7 and Flex. I'm trying to use custom classes between the client and server.
In as:
package
{
[Bindable]
[RemoteClass(alias="remoting.Product")]
public class Product
{
public var name:String;
public var id:int;
public var isVisible:Boolean;
}
}
In Java:
package remoting;
public class Product {
public String name;
public int id;
public Boolean isVisible;
public Product(){
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public void setId(int _id){
id = _id;
}
public void setVisible(Boolean _isVisible){
isVisible = _isVisible;
}
}
Service part:
public Product echo() {
Product product = new Product();
product.setId(123);
product.setName("My Product");
product.setVisible(true);
return product;
}
I can successfully set the destination of the RemoteObject and call the echo() method. The result event fires up, with the Product object in event.result. However, it does not contain any sensible data. The variables from AS class just get initialized with null, 0 and true values. I'm wondering what's the problem. I tried returning a String with parameters from Product and it works fine, so they get set fine. The problem is in mapping.
I could go another way and implement Externalizable but I don't understand this part from the example:
name = (String)in.readObject();
properties = (Map)in.readObject();
price = in.readFloat();
What if there is a number of strings?
Cheers.
In java class: use private fields and implement getters.
package remoting;
public class Product {
private String name;
private int id;
private Boolean isVisible;
public Product() {
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public String getName(){
return name;
}
public void setId(int _id){
id = _id;
}
public int getId(){
return id;
}
public void setIsVisible(Boolean _isVisible){
isVisible = _isVisible;
}
public Boolean getIsVisible() {
return isVisible;
}
}
You could also switch from BlazeDS to GraniteDS: the latter has a powerful transparent externalization mechanism as well as code generation tools that can really save your time (see documentation here).

create a class to model a list

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Categories