ArrayList [] set = new ArrayList[n]; - arraylist

What is this ??
ArrayList [] set = new ArrayList[n];
Implementation of arraylist is:
ArrayList Integer> al = new ArrayList Integer> ();

The first what you had defined
ArrayList [] set = new ArrayList[n];
This is an array of ArrayList. As we know that ArrayList is a class. So the first statement defines the array of ArrayList class.
The second example is
ArrayList Integer> al = new ArrayList Integer> ();
Here you are creating the object of ArrayList. So here you are creating an object of ArrayList class and will be adding values in it.
Below is an example that contains the use of both
public class Testing {
public static void main(String[] args) {
ArrayList[] set = new ArrayList[10];
ArrayList<String> list = new ArrayList<String>();
list.add("RHV");
list.add("Zen");
set[0] = list;
System.out.println(set[0]);
}
}

Related

JAVA. Convert ListArray to List

Why doesn't the code work?
List<String> list = new ArrayList<>();
//or
List list = new ArrayList<String>();
//or
List<String> list = new ArrayList<String>();
//or
List list = new ArrayList();
How i understand, list is interface. ArrayList implemented list. Why doesn't type conversion work?

Assigning list of HashMap to another list of HashMap as method return value

I am trying to assign a method's return value to a List of HashMaps.
Method returning List
public List<HashMap<String, String>> getDetails() {
List<HashMap<String, String>> info = new ArrayList<HashMap<String, String>>();
HashMap<String, String> components = new HashMap<String, String>();
//Fetched some result from DataBase in ResultSet (assume i have fetched three rows).
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
components.put("id", rs.getString("id"));
components.put("columnA", rs.getString("columnA"));
components.put("columnB", rs.getString("columnB"));
components.put("columnC", rs.getString("columnC"));
components.put("columnD", rs.getString("columnD"));
info.add(components);
}
return info;
}
Calling Method
public void dispDetails(){
List<HashMap<String, String>> info = new ArrayList<HashMap<String, String>>();
details = getDetails();
for(int i=0;i<3;i++){
System.out.println(details.get(i).get("id"));
System.out.println(details.get(i).get("columnA"));
System.out.println(details.get(i).get("columnB"));
System.out.println(details.get(i).get("columnC"));
System.out.println(details.get(i).get("columnD"));
}
}
But somehow all the values in the calling methods list(i.e dispDetails) are same.
Is there any way to assign the list.

Unable to cast object of type '<>f__AnonymousType1`1[System.String]' to type

I'm trying to follow the answer from this Stack Overflow question regarding a custom Image Link helper. The code works, as long as I remove the .MergeAttributes command. When used, this command blows up, throwing the following exception
Unable to cast object of type '<>f__AnonymousType11[System.String]' to type 'System.Collections.Generic.IDictionary2[System.String,System.String]'.
Below is the code from the helper class I'm using. The idea was to only use two string values as input parameters, and any other HTML/img tag attributes input as properties of the input objects.
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string url, object imgAttributes, object htmlAttributes)
{
UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
var imgTag = new TagBuilder("img");
imgTag.MergeAttribute("src", imgSrc);
imgTag.MergeAttributes((IDictionary<string, string>)imgAttributes, true); //Exception thrown here
var imgLink = new TagBuilder("a");
imgLink.MergeAttribute("href", url);
imgLink.InnerHtml = imgTag.ToString();
imgLink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true);
return MvcHtmlString.Create(imgLink.ToString());
}
And here is the code from the Razor/.cshtml file.
#Html.ImageLink(Url.Content("~/Content/images/Screen.PNG"), System.Configuration.ConfigurationManager.AppSettings["Periscope"],
new {title="Search Periscope"} , new { target="_blank"})
You can use the AnonymousObjectToHtmlAttributes() method of HtmlHelper to cast your object. Replace the following lines
imgTag.MergeAttributes((IDictionary<string, string>)imgAttributes, true);
imgLink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true);
with
imgTag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(imgAttributes), true);
imgLink.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), true);
The way you are casting is not seems valid.
use this following extension method to make it working.
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string url, object imgAttributes, object htmlAttributes)
{
UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
var imgTag = new TagBuilder("img");
imgTag.MergeAttribute("src", imgSrc);
var color = imgAttributes.ToDictionary<string>();
imgTag.MergeAttributes(color, true); //No moer Exception thrown here
var imgLink = new TagBuilder("a");
imgLink.MergeAttribute("href", url);
imgLink.InnerHtml = imgTag.ToString();
imgLink.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
return MvcHtmlString.Create(imgLink.ToString());
}
public static IDictionary<string, object> ToDictionary(this object source)
{
return source.ToDictionary<object>();
}
public static IDictionary<string, T> ToDictionary<T>(this object source)
{
if (source == null)
ThrowExceptionWhenSourceArgumentIsNull();
var dictionary = new Dictionary<string, T>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
AddPropertyToDictionary<T>(property, source, dictionary);
return dictionary;
}
private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
{
object value = property.GetValue(source);
if (IsOfType<T>(value))
dictionary.Add(property.Name, (T)value);
}
private static bool IsOfType<T>(object value)
{
return value is T;
}
private static void ThrowExceptionWhenSourceArgumentIsNull()
{
throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
}

Nested foreach with Map does not work properly in Velocity

I want to generate below code snippet using Velocity.
Map<String, List<String>> fruitsAndTypesMap = new HashMap<String, List<String>>();
String fruit_Apple = "Apple";
List<String> types_Apple = new ArrayList<String>();
types_Apple.add("KA");
types_Apple.add("WA");
fruitsAndTypesMap.put(fruit_Apple, types_Apple);
String fruit_Orange = "Orange";
List<String> types_Orange = new ArrayList<String>();
types_Orange.add("HO");
types_Orange.add("LO");
fruitsAndTypesMap.put(fruit_Orange, types_Orange);
My template_fruits.vm file is as below.
#if ($fruitsMap.size()>0)
Map<String, List<String>> fruitsAndTypesMap = new HashMap<String,List<String>>();
#foreach( $fruitName in $fruitsMap.keySet() )
String fruit_$fruitName = "$fruitName";
List<String> types_$fruitName = new ArrayList<String>();
#foreach( $fruitType in $fruitsMap.get($fruitName) )
types_$fruitName.add("$fruitType.name");
#end
fruitsAndTypesMap.put(fruit_$fruitName, types_$fruitName);
#end
#end
Issue is with the statement: types_$fruitName.add("$fruitType.name");
it does not evaluate the $fruitName properly.
But if i modify the statement to be like: types_($fruitName).add("$fruitType.name");, it is evaluated properly but the value is surrounded with brackets. I dont understand the brackets trick for evaluation.
Below code can be used to load $fruitsMap
public static Map<String, List<Fruit>> getFruitsMap(){
Map<String, List<Fruit>> fruitsMap = new HashMap<String, List<Fruit>>();
List<Fruit> applesList = new ArrayList<Fruit>();
Fruit fruit_Apple = null;
fruit_Apple = new Fruit(); fruit_Apple.setName("KA");
applesList.add(fruit_Apple);
fruit_Apple = new Fruit(); fruit_Apple.setName("WA");
applesList.add(fruit_Apple);
List<Fruit> orangesList = new ArrayList<Fruit>();
Fruit fuit_Orange = null;
fuit_Orange = new Fruit(); fuit_Orange.setName("HO");
orangesList.add(fuit_Orange);
fuit_Orange = new Fruit(); fuit_Orange.setName("LO");
orangesList.add(fuit_Orange);
fruitsMap.put("Apple", applesList);
fruitsMap.put("Orange", orangesList);
return fruitsMap;
}
Code related to template execution:
VelocityEngine velEngine = new VelocityEngine();
velEngine.init();
Template template = velEngine.getTemplate("template_fruits.vm");
VelocityContext context = new VelocityContext();
context.put("fruitsMap", FruitClient.getFruitsMap());
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println("Content: " + writer.toString());
Any hints of what is the wrong with the statement--> types_$fruitName.add("$fruitType.name"); will be helpful.
Thanks
The statement should be:
types_${fruitName}.add("$fruitType.name");
Otherwise, Velocity tries to call an add method on the $fruitName object.

Distributed Cache in Pig UDF

Here is my code to Implement a UDF using Distributed Cache Using Pig.
public class Regex extends EvalFunc<Integer> {
static HashMap<String, String> map = new HashMap<String, String>();
public List<String> getCacheFiles() {
Path lookup_file = new Path(
"hdfs://localhost.localdomain:8020/user/cloudera/top");
List<String> list = new ArrayList<String>(1);
list.add(lookup_file + "#id_lookup");
return list;
}
public void VectorizeData() throws IOException {
FileReader fr = new FileReader("./id_lookup");
BufferedReader brd = new BufferedReader(fr);
String line;
while ((line = brd.readLine()) != null) {
String str[] = line.split("#");
map.put(str[0], str[1]);
}
fr.close();
}
#Override
public Integer exec(Tuple input) throws IOException {
// TODO Auto-generated method stub
return map.size();
}
}
Given Below is my Distributed Cache Input File (hdfs://localhost.localdomain:8020/user/cloudera/top)
Impetigo|Streptococcus pyogenes#Impetigo
indeterminate leprosy|Uncharacteristic leprosy#indeterminate leprosy
Output I get is
(0)
(0)
(0)
(0)
(0)
This means that my hashmap is empty.
How do i fill my hashmap using Distributed Cache?.
This was because VectorizeData() was not called in the executable.