Java: How to get data from ArrayList<Data Type> - arraylist

I'm trying to make an app that manages contacts. I'm having difficulty getting the data within those contacts.
This is my ContactsManager class
public class ContactsManager {
private ArrayList<Contact> contacts = new ArrayList<Contact>();
public void createContact(String name, String phoneNumber){
Contact contact = new Contact(name, phoneNumber);
contacts.add(contact);
}
}
And This is my Contact class
public class Contact {
private String name, phoneNumber;
public Contact(String name, String phoneNumber){
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName(){
return name;
}
public String getNumber(){
return phoneNumber;
}
}
How would I go about getting the Names and Numbers that I pass into the ArrayList? Thank You

After you add the entry in the list, you only need to get by position, like:
Contact firstContact = contacts.get(0);
firstContact.getName();
firstContact.getNumber();
Or for all contacts:
contacts.forEach(contact -> {
System.out.println(contact.getName());
System.out.println(contact.getNumber());
});

Related

How to send object which contains IEnumerable via Refit on NetCore?

I have to send a request object via Refit which contains 2 IEnumerable and one string, but for some reason I can't send the object forward.
I've tried to use all the paramets from the interface. Ex: [Query(CollectionFormat.Csv)] or Multi / Pipes but no success.
I've also tried to create my own CustomUrlParameterFormatter but unfortunately here I'm stuck, because I don't see a good way to retrieve the name of the property from the object request that I'm sending.
The code for CustomUrlParameterFormatter
public class CustomUrlParameterFormatter : IUrlParameterFormatter
{
public string Format(object value, ParameterInfo parameterInfo)
{
if(value is IEnumerable enumerable)
{
var result = ToQueryString(enumerable, parameterInfo.Name);
return result;
}
return string.Empty;
}
public static string ToQueryString(IEnumerable query, string parameterName)
{
var values = query.Cast<object>().Select(ToString).ToArray();
var separator = parameterName + "=";
return values.Any() ? separator + string.Join("&" + separator, values) : "";
}
public static string ToString(object value)
{
var json = JsonConvert.SerializeObject(value).Replace("\\\"", "\"").Trim('"');
return Uri.EscapeUriString(json);
}
}
The Call from the IService that I'm using
[Get("/TestMethod")]
Task<HttpResponseMessage> TestMethod([Query]TestRequestDTO requestDTO, [Header("X-Correlation-ID")] string correlationId);
The Request object
public class TestRequestDTO
{
public IEnumerable<long> EnumOne { get; set; }
public IEnumerable<long> EnumTwo { get; set; }
public string MethodString { get; set; }
}
Also the RefitClient configuration
var refitSettings = new RefitSettings();
refitSettings.UrlParameterFormatter = new CustomUrlParameterFormatter();
services.AddRefitClient<IService>(refitSettings)
.ConfigureHttpClient(c => c.BaseAddress = new Uri(settings.Services.IService));
What I'm trying to achieve is something like
TestMethod?EnumOne =123&EnumOne =321&EnumTwo=123&EnumTwo=321&methodString=asdsaa
and instead I'm receiving other behavior
without CustomUrlParameterFormatter()
TestMethod?EnumOne=System.Collections.Generic.List`1%5BSystem.Int64%5D&EnumTwo=System.Collections.Generic.List`1%5BSystem.Int64%5D&MethodString=sdf

Create complex class with factory and builder

background:
I build a class diagram for shopping on the net.
For creating a user interface with tow type (golden-User and silver-User) I use the factory pattern.
But the User class become to be very complex.
How can I create this class by bulider and on the other hand the ability to specify the user type such as the factory will remain on the class name
(will help me to recognize which type is by polymorphism and not by if&else)
The Decorator pattern is a simple solution:
public class Main {
public static void main(String[] args) {
User silverUser = new UserDecorator(new SilverUser("Kyriakos", "Georgiopoulos"));
User goldenUser = new UserDecorator(new GoldenUser("GoldenUser firstName", "GoldenUser lastName"));
User nullUser = new UserDecorator(null);
System.out.println(silverUser.firstName() + " " + silverUser.lastName() + " is " + silverUser.type());
System.out.println(goldenUser.firstName() + " " + goldenUser.lastName() + " is " + goldenUser.type());
System.out.println(nullUser.firstName() + " " + nullUser.lastName() + " is " + nullUser.type());
}
}
interface User {
String firstName();
String lastName();
String type();
}
class SilverUser implements User {
private final String firstName;
private final String lastName;
SilverUser(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
public String type() {
return "SilverUser ";
}
}
class GoldenUser implements User {
private final String firstName;
private final String lastName;
GoldenUser(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
public String type() {
return "GoldenUser ";
}
}
class UserDecorator implements User {
private final User user;
UserDecorator(User user){
this.user = user;
}
public String firstName() {
return user != null && user.firstName() != null && user.firstName().length() > 0 ?
user.firstName() : "";
}
public String lastName() {
return user != null && user.lastName() != null && user.lastName().length() > 0 ?
user.lastName() : "";
}
public String type() {
return user != null ? user.type() : "NullPointerException";
}
}
The intent of the two patterns are different: while Factory creates an object instance (which can hold more other class instances) the Builder's goal is to create object step-by-step and reduce overloaded constructors.
For example (with java snippets):
Factory method
interface for user:
public interface User {
}
GoldUser class:
class GoldUser implements User {
// ... field declarations
// Ctor
GoldUser(fields...){}
// ... methods
}
SilverUser class:
class SilverUser implement User {
// ... field declarations
// Ctor
SilverUser(fields...){}
// ... methods
}
User Factory Class:
public class UserFactory {
// ... user versions
public static int GoldUser = 0;
public static int SilverUser = 1;
// ... private Ctor because we don't want to instantiate this class - only in this example
private UserFactory (){}
// ... creating appropriate User instance
public static User createUser(int userType){
switch (userType){
case GoldUser: return new GoldUser;
case SilverUser: return new SilverUser;
default throw new WrongUserTypeException("Wrong User Type");
}
}
}
in your other class:
// ... code stuff here
User user=UserFactory.createUser(1); // will return new SilverUser instance
// ... other code stuff here
Builder pattern
If you have many fields in your class and only some of them are compulsory, you don't have to create many constructors, a builder will enough:
class UserBuilder{
private static Service_A serviceA; // required
private static Service_B serviceB; // required
private static Service_C serviceC;
private static Service_D serviceD;
private static Service_E serviceE;
// since this builder is singleton
private static UserBuilder builderInstance = new UserBuilder();
private UserBuilder () {};
public static UserBuilder getBuilderInstance (Service_A service_A, Service_B service_B){
serviceA = service_A;
serviceB = service_B;
serviceC = null;
serviceD = null;
serviceE = null;
return builderInstance;
}
public static UserBuilder addServiceC (Service_C service_C) {
serviceC = service_C;
return builderInstance;
}
public static UserBuilder addServiceD (Service_D service_D) {
serviceC = service_D;
return builderInstance;
}
public static UserBuilder addServiceE (Service_E service_E) {
serviceE = service_E;
return builderInstance;
}
public static User build(){
return new User (serviceA, ServiceB, ServiceC, ServiceD, ServiceE);
}
And later you can build a customized User:
UserBuilder aUserBuilder = UserBuilder.getBuilderInstance(aServiceA, aServiceB);
// ... other stuff
aUserBuilder.addServiceE(aServiceE);
///... more stuff
User aUser= aUSerBuilder.addServiceC(aServiceC)
.build(); // will return the fresh built User instance
Hope I could help you!
Regards,
Cs
In this particular case you're not supposed to use Factory to create different instances of the same class. It can be used to create different implementations of one common abstraction. Try implementing IUser interface. Then implement this interface by two classes: GoldenUser and SilverUser. Your Factory will create instance of either GoldenUser or SilverUser and return it as IUser. Also instead of interface IUser you could probably create User abstract class, that will be inherited by GoldenUser and SilverUser.

Why am I getting "java.lang.NullPointerException" w/ my ArrayList?

I am making a class to deal with a friend list scenario using an ArrayList and I'm not sure what I have done wrong. The "java.lang.NullPointerException" occurred the moment I called the addFriend method and I can't seem to troubleshoot exactly why this is happening. Please give me some hints in the right direction!
public class Person {
private String name;
private ArrayList<String> friends;
public Person(String name) {
this.name = name;
this.friends = friends;
}
public String getName() {
return this.name;
}
public void addFriend(String friend) {
friends.add(friend);
}
public boolean hasFriend(String name) {
for(String friend : this.friends) {
if(name.equals(friend)) {
return true;
}
}
return false;
}
public String getFriends() {
String stringOfFriends=friends.toString();
return stringOfFriends;
}
public String unfriend(String friend) {
if (friends.contains(friend)) {
friends.remove(friend);
}
return friends.toString();
}
}
Your Constructor has to initialze the Arraylist:
public Person(String name) {
this.name = name;
this.friends = new ArrayList<String>();
}
In your current version, you assign the ArrayList "friends" to itself. That means you basically call this.frinds = this.friends and this.friends is not initialzed yet hence the NullpointerException.
In your constructor this.friends = friends; doesn't make sense. Make like this
public Person(String name,ArrayList<String> friends) {
this.name = name;
this.friends = friends;
}
Then pass the actual arraylist to the constructor.
You need to initialize your array list. Like private ArrayList<String> friends = new ArrayList<String>(); or in the constructor as below:
public Person(String name) {
this.name = name;
this.friends = new ArrayList<String>();
}

Spring-data-solr config

i met a problem in Studying with Spring data solr,this is my Configuration Class:
#Configuration
#EnableSolrRepositories(basePackages={"cn.likefund.solr.repository"}, multicoreSupport=true)
public class SolrContext {
static final String SOLR_HOST = "http://192.168.11.157:8080/solr";
#Bean
public SolrClient solrClient() {
return new HttpSolrClient(SOLR_HOST);
}
}
and this is my Repository:
package cn.likefund.solr.repository;
import java.util.List;
import org.springframework.data.solr.repository.SolrCrudRepository;
import cn.likefund.solr.model.Activity;
public interface ActivityRepository extends SolrCrudRepository<Activity, String>{
List<Activity> findByName(String name);
}
when I start the application,the message in console is this
error
When I delete the method findByName in the repository,the application start with no problem, i just want to the method findByName worked,anybody know what should i do with this problem?
here is the Activity Class:
#Entity
#SolrDocument(solrCoreName ="core_activity")
public class Activity implements Serializable{
private static final long serialVersionUID = 1566434582540525979L;
#Id
#Field(value = "id")
private String id;
#Field(value = "CREATEDT")
private String createdt;
#Indexed
#Field(value = "NAME")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCreatedt() {
return createdt;
}
public void setCreatedt(String createdt) {
this.createdt = createdt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So, obviously the CrudRepository is not created .
when you delete the findByName, can you manually query your repo ? (just to be sure the problem comes from the method, and not the SOLR schema)
have you tried to annotate annotate the method to explicitly set the query ? Something like
#Query("NAME:?0")
List findByName(String name);

Arraylist can't add element

Why isn't this working for me?
public class Band {
public void addMember(Musician musician) {
musicians.add(musician);
System.out.println("Muscian: " + musician + "was successfully added");
}
}
public static void main(String[] args) {
Band Beatles = new Band("Beatles");
Beatles.addMember("John Lennon");
}
public class Musician {
private String name;
public Musician(String name, Instrument instrument) {
this.name = name;
Instrument Guitar = instrument;
}
public void play() {
}
}
Beatles.addMember("John Lennon");
should be
Beatles.addMember(new Musician("John Lennon", new Instrument(new Guitar()));
I suspect, without seeing your actual Instrument class, based on your comment that this line should work.
The problem is that you are treating some objects as Strings. You need to create the object out of the class that defines it first.