here is the code of C# which i am trying to convert
ArrayList.BinarySearch(Object, IComparer)
what it does is to comparer a node class object with a compare class object and returns -1, 0 or positive integer.
i have searched a lot and tried to convert it in java but could not do so. i'll need a method, instructions, library or anything that could help me achieve it.
class Class1
{
[STAThread]
static void Main(string[] args)
{
ArrayList SolutionPathList = new ArrayList();
//Create a node containing the goal state node_goal
Node node_goal = new Node(null,null,1,15,15);
//Create a node containing the start state node_start
Node node_start = new Node(null,node_goal,1,0,0);
//Create OPEN and CLOSED list
SortedCostNodeList OPEN = new SortedCostNodeList ();
SortedCostNodeList CLOSED = new SortedCostNodeList ();
//Put node_start on the OPEN list
OPEN.push (node_start);
}
SortedNode class is:
public class SortedCostNodeList
{
ArrayList _list;
NodeComparer _nodeComparer;
public SortedCostNodeList()
{
_list = new ArrayList ();
_nodeComparer = new NodeComparer ();
}
public int push (Node n)
{
int k = _list.BinarySearch (n,_nodeComparer);
if (k==-1) // no element
_list.Insert (0,n);
else if (k<0) // find location by complement
{
k=~k;
_list.Insert (k,n);
}
else if (k>=0)
_list.Insert (k,n);
return k;
}
and nodecomparer class is:
public class NodeComparer:IComparer
{
public NodeComparer()
{
}
public int Compare(object x, object y)
{
return ((Node)x).totalCost - ((Node) y).totalCost ;
}
}
i am unable to implement this piece of code
//int k = _list.BinarySearch (n,_nodeComparer);
any help?
You can use Arrays.binarySearch() to perform binary search on an array of Object.
I have created a sample program. Hope it helps.
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
#Getter #Setter
#AllArgsConstructor
class Node {
private long totalCost;
}
public class StackOverFlow {
public static void main(String... args) {
final List<Node> list = new ArrayList<>();
list.add(new Node(10));
list.add(new Node(20));
list.add(new Node(30));
list.add(new Node(40));
list.add(new Node(50));
list.add(new Node(60));
list.add(new Node(70));
final Node searchKey = new Node(60);
int index = Arrays.binarySearch(list.toArray(new Node[list.size()]), searchKey, new Comparator<Node>() {
#Override
public int compare(Node o1, Node o2) {
return (int) (o1.getTotalCost() - o2.getTotalCost());
}
});
System.out.print("Found at " + index);
}
}
Update:
Try this
class NodeComparator implements Comparator<Node> {
#Override
public int compare(Node o1, Node o2) {
return (int) (o1.getTotalCost() - o2.getTotalCost());
}
}
class SortedCostNodeList {
ArrayList<Node> list;
NodeComparator nodeCompartor;
public SortedCostNodeList() {
this.list = new ArrayList<>();
this.nodeCompartor = new NodeComparator();
}
public int push(Node n) {
int k = Arrays.binarySearch(this.list.toArray(new Node[list.size()]), n, this.nodeCompartor);
if (k == -1) // no element
this.list.add(0, n);
else if (k < 0) // find location by complement
{
k = ~k;
this.list.add(k, n);
} else if (k >= 0)
this.list.add(k, n);
return k;
}
// ...
}
Related
Are there any cases in which getFirst() and getLast() show the same element when using the LinkedList provided by Collections?
I am parsing data to staging variables to be held; then I am storing these variables in a new object to be stored in my LinkedList using the add() method. However, when I am printing out statements, after every time an object is added to my LinkedList, by using the getFirst() and getLast() they are pointing to the same object?
Please see code below (please dont critic the code too much, I am only a beginner so I know it isn't pretty, but it recreates my problem)
public class Main {
public static void main(String[] args) {
Parse parse = new Parse();
parse.main();
}
}
import java.lang.reflect.Array;
public class Parse {
String[] input = {"1", "a",
"2", "b",
"3","c",
"4", "d"};
Object tempObject = new Object();
String tempLength;
String tempFilename;
int arrayIndex = 0;
public static ObjectList objectList = new ObjectList();
Parse(){
}
public void main() {
for (int i = 0; i != input.length; i++) {
String stringInput = iterateInputArray(input, i);
addToTempObject(stringInput);
Object finalObject = new Object();
finalObject = tempObject;
Object tempObject = new Object();
objectList.addToList(finalObject);
System.out.println("First:" + ObjectList.listOfObjects.getFirst());
System.out.println("Last:" + ObjectList.listOfObjects.getLast());
}
}
public String iterateInputArray(String[] input, int arrayIndex){
String string = input[arrayIndex];
return string;
}
private void addToTempObject(String inputString){
if (tempLength == null){
tempLength = inputString;
tempObject.setLength(inputString);
}
else {
tempObject.setFilename(inputString);
tempFilename = inputString;
resetTempVariables();
}
}
private void resetTempVariables() {
tempLength = null;
tempFilename = null;
}
}
public class Object {
private String length;
private String filename;
public Object( String length, String filename) {
this.length = length;
this.filename = filename;
}
public Object(){
this.length = null;
this.filename = null;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setLength(String length) {
this.length = length;
}
public String getLength() {
return this.length;
}
public String getFilename() {
return this.filename;
}
}
import java.util.LinkedList;
public class ObjectList extends Object {
public static LinkedList<java.lang.Object> listOfObjects = new
LinkedList<java.lang.Object>();
public ObjectList() {
}
public void addToList(Object object){
listOfObjects.add(object);
}
}
I reduced the code. The reduced code is, for the discussion of the prorblem, identical to the provided code:
import java.util.LinkedList;
class Scratch {
public static final Object tempObject = new Object();
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
for (int i = 0; i != 10; i++) {
list.add(tempObject);
System.out.printf("First: %s, Last: %s, Size: %d%n",
list.getFirst(),
list.getLast(),
list.size());
}
}
}
Ideone demo
The code keeps adding one and the same object (tempObject) to the list. Notice the final keyword introduced to highlight that variable tempObject references the same object over its whole lifetime. Thus, the size of the list grows, but the list contains the same object, over and over again. This is why getFirst() and getLast() return the same object.
The problem can be fixed by, e.g., moving the declaration of tempObject in the loop:
import java.util.LinkedList;
class Scratch {
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
for (int i = 0; i != 10; i++) {
final Object tempObject = new Object();
list.add(tempObject);
System.out.printf("First: %s, Last: %s, Size: %d%n",
list.getFirst(),
list.getLast(),
list.size());
}
}
}
Ideone demo
yes, a linked list with one element. like following test
import static org.assertj.core.api.Assertions.assertThat
class ListSpec extends Specification{
def "linked list with one elem"(){
given: "a linked list with one element"
LinkedList<String> list = new LinkedList<>()
list.add("test")
expect:"last and first element are same"
assertThat(list.getFirst()).isEqualTo(list.getLast())
}
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerSet {
public static final <E> Collection<Set<E>> of(Set<E> s) {
List<E> src = new ArrayList<>(s);
if (src.size() > 30) {
throw new IllegalArgumentException("Set too big " + s);
}
return new AbstractList<Set<E>>() {
#Override
public int size() {
return 1 << src.size(); // 2 to the power srcSize
}
#Override
public boolean contains(Object o) {
return o instanceof Set && src.containsAll((Set) o);
}
#Override
public Set<E> get(int index) {
Set<E> result = new HashSet<>();
for (int i = 0; index != 0; i++, index >>= 1) {
if ((index & 1) == 1) {
result.add(src.get(i));
}
}
return result;
}
};
}
public static void main(String[] args) {
Collection<Set<String>> set = new HashSet<>();
set.add()... }
I have this code I got from Java Effective as how implement
power set but I am confused how to initialise this set and
fill it with values. There is interface with three overridden
methods, concretely contains, get and size. What does of in class
declaration mean?
To initialize PowerSet instance you need to call it's constructor PowerSet(), though it'll be useless since there is no object related underlying logic in it.
"of" is a static method declared in PowerSet, accepting a set with size <= 30 and returning a List of Sets with logic of power set.
It is implemented by extension of AbstractList.
Set<Long> input = new HashSet<Long>();
input.add(1L);
input.add(2L);
List<Set<Long>> example = PowerSet.<Long>of(input);
So, example.get(0) will result with an empty HashSet, example.get(1) == {1}; example.get(2) == {2}, example.get(3) == {1, 2}
You can rewrite it in a more conventional format:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerSet<E> extends AbstractList<Set<E>> {
private List<E> src;
public PowerSet(Set<E> s){
//copying set contains to a list to access by index
src = new ArrayList<>(s);
}
#Override
public int size() {
return 1 << src.size(); // 2 to the power srcSize
}
#Override
public boolean contains(Object o) {
return o instanceof Set && src.containsAll((Set) o);
}
#Override
public Set<E> get(int index) {
Set<E> result = new HashSet<>();
for (int i = 0; index != 0; i++, index >>= 1) {
if ((index & 1) == 1) {
result.add(src.get(i));
}
}
return result;
}
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add()...
PowerSet<String> = new PowerSet(set);
}
This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 4 years ago.
I am maintaining a sorted ArrayList of objects (by overwriting the add method as shown here) where each object has 2 attributes: a and b. How can I retrieve an object for which a equals 5?
I cannot use a map, because the value which I want to sort the list on must be able to accept duplicates (which is why this answer is not applicable here).
Code:
class TimeMap {
List<MyType> list = new ArrayList<KVT>() {
public boolean add(KVT mt) {
int index = Collections.binarySearch(this, mt, new SortByTime());
if (index < 0) index = ~index;
super.add(index, mt);
return true;
}
};
}
class KVT{//value-timestamp object
String value;
int timestamp;
public VT(String v, int t){
value=v;
timestamp=t;
}
}
class SortByTimestamp implements Comparator<KVT>{
public int compare(KVT a, KVT b){
return a.timestamp.compareTo(b.timestamp);
}
}
I have written a small example using java8 streams where you can get the object from the ArrayList by a property of the object.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Test> list = Arrays.asList(new Test(1, 2), new Test(5, 6), new Test(3, 4));
Test test = list.stream().filter(obj -> obj.a == 5).findFirst().orElse(null);
System.out.println(test.a);
}
}
class Test {
int a;
int b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
}
Hope this will give you an idea
Here is an mcve demonstrating retrieval by timestamp as well as some other enhancement:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TimeMap {
private List<KVT> list;
TimeMap() {
list = new ArrayList<>() {
#Override
public boolean add(KVT mt) {
super.add(mt); //add
Collections.sort(this, new SortByTimestamp()); //resort after add
return true;
}
};
}
boolean add(KVT mt){return list.add(mt);}
KVT getByTimeStamp(int timestamp){
for(KVT mt : list){
if(timestamp == mt.timestamp)
return mt;
}
return null;
}
//returns a copy of list
List<KVT> getListCopy() { return new ArrayList<>(list) ;};
//test
public static void main(String[] args) {
TimeMap tm = new TimeMap();
tm.add(new KVT("A", 2));
tm.add(new KVT("B", -3));
tm.add(new KVT("C", 1));
System.out.println(tm.getListCopy());
System.out.println(tm.getByTimeStamp(1));
}
}
class KVT{
String value;
int timestamp;
public KVT(String v, int t){
value=v;
timestamp=t;
}
#Override
public String toString(){ return value+" ("+timestamp+")";}
//todo add getters
}
class SortByTimestamp implements Comparator<KVT>{
#Override
public int compare(KVT a, KVT b){
//compareTo can not be applied to primitives
return Integer.valueOf(a.timestamp).compareTo(b.timestamp);
}
}
I am working on some kind of software delivery tool. For one of its task the program needs to find the class file names which will generate after compiling any given java file.
I need some kind of parsing library/approach which can detect all inner
classes(named as well as anonymous) too.
e.g.: If input file contains below code. Our program should generate output as: SampleClass1.class, SampleClass1$Data.class, SampleClass1$1.class
package com.aci.uob.patchmanifest.helper.testapp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SampleClass1 {
public static String CONSTANT_ATTR = "Sample String Constant";
int attr;
boolean b;
private class Data implements Comparable<Data>{
String val="--";
public Data(String val) {
super();
this.val = val;
}
#Override
public int compareTo(Data o) {
return this.val.compareTo(o.val);
}
}
public SampleClass1(int attr, boolean b) {
super();
System.out.println("this is a sample constructor");
this.attr = attr;
this.b = b;
}
private void runInnerClasses(){
List<Data> list=new ArrayList<Data>();
list.add(new Data("Hello"));
list.add(new Data("World"));
list.add(new Data("20"));
list.add(new Data("100"));
list.add(new Data(" Hello"));
Collections.sort(list);
printList(list);
Collections.sort(list, new Comparator<Data>() {
#Override
public int compare(Data o1, Data o2) {
// TODO Auto-generated method stub
return o1.val.trim().compareToIgnoreCase(o2.val.trim());
}
});
}
private void printList(List<Data> list) {
for(Data d: list)
System.out.println(d.val);
}
}
If your program are running under Eclipse, JDT API(org.eclipse.jdt.core plugin) is a choice. Here is a example:
IJavaElement ele = JavaCore.create(ifile);
if (ele instanceof ICompilationUnit) {
IType[] czs = ((ICompilationUnit)ele).getAllTypes();
for (int i = 0; i < czs.length; i++) {
System.out.println(czs[i].getTypeQualifiedName());
//IType.getFullyQualifiedName() will return value include package name
IMethod[] ims = czs[i].getMethods();
for (int j = 0; j < ims.length; j++) {
IJavaElement[] childs = ims[j].getChildren();
//find anonymous type inside Method
for (int k = 0; k < childs.length; k++) {
if (childs[k] instanceof IType) {
System.err.println(((IType)childs[k]).getTypeQualifiedName());
}
}
}
}
}
Output example:
SampleClass1
SampleClass1$Data
SampleClass1$1
The JDT core API doesn't handle naming of anonymous types.
If private void printList(List list) also include a anonymous type.
The API also return SampleClass1$1.
You may also need czs[i].getFields() to find anonymous type inside Field. If SampleClass1 declare a class variable like:
Runnable r = new Runnable() {
public void run(){};
};
public X get(int index)
{
if (index >= 0)
{
Node<X> i = head;
int c = 0;
while (c < index)
{
i = i.getLink();
c++;
}
return i.getValue();
}
else
{
throw new ArrayIndexOutOfBoundsException();
}
}
.
#Test
public void testGet12()
{
LList<String> b = new LList<String>();
b.add("str1");
b.add("str2");
b.add("str3");
b.add("str4");
b.add("str5");
b.add("str6");
b.add("str7");
b.add("str8");
b.add("str9");
b.add("str10");
b.add("str11");
b.add("str12");
assertEquals("str8", b.get(7));
assertEquals("str12", b.get(11));
assertEquals("str1", b.get(0));
}
It is saying that it's expecting str8, but is getting str5, why is my index off by 3? Am i missing something here? To me it seems when it doesnt reach the index it goes up one link until it finally reaches it then spits out the value.
Just an idea
import java.util.ArrayList;
import java.util.List;
public class list {
static List<String> a=new ArrayList<String>();
public String getvalue(int index)
{
return a.get(index);
}
public static void main(String args[]){
list e=new list();
a.add("Str0");
a.add("Str1");
a.add("Str2");
a.add("Str3");
a.add("Str4");
a.add("Str5");
a.add("Str6");
a.add("Str7");
a.add("Str8");
if("Str6".equals(e.getvalue(6))){
System.out.println("true");
}
else
System.out.println("Wrong");
}
}