i have the code like this when i create it like this
public final class PhpArray extends AbstractMap
{
private TreeMap t;
private HashMap m;
public PhpArray() {
this.t = new TreeMap(Request.PHP_ARRAY_KEY_COMPARATOR);
this.m = null;
}
#Override
public Object put(final Object key, final Object value) {
if (this.m != null) {
return this.m.put(key, value);
}
try {
return this.t.put(key, value);
}
catch (ClassCastException e) {
this.m = new HashMap(this.t);
this.t = null;
return this.m.put(key, value);
}
}
#Override
public Set entrySet() {
if (this.t != null) {
return this.t.entrySet();
}
return this.m.entrySet();
}
public int arraySize() {
if (this.t == null) {
throw new IllegalArgumentException("The passed PHP \"array\" is not a sequence but a dictionary");
}
if (this.t.size() == 0) {
return 0;
}
return 1 + this.t.lastKey();
}
}
but when i update my project i got error in the code
return 1 + this.t.lastKey();
the error is an arguments + is undefined.. why like that ? and how to fix the problem ?
TreeMap is a generic class but in the code in your question you have used it without type parameters. This means that this line of your code:
private TreeMap t;
is essentially this:
private TreeMap<Object, Object> t;
In other words t.lastKey() returns an Object and the operator + can't be used with Object because an Object is not a number.
Perhaps you meant to call method size() rather than method lastKey()?
Perhaps this tutorial will help?
I have implemented a class named BusinessData. The constructor takes a number of double arrays, but I want the double arrays to be immutable, so I have implemented this class a value object. I used an immutable collection for the double arrays.
However, I am getting an OutOfMemoryError: Java Heap Space. I think it has something to do with the garbage collection and the converting of array to List, then converting it back to an array. I am doing this since I am unable to change the constructor, or the method signature.
Are there any better solutions that use less memory? I understand that my implementation uses a lot of memory. Thank you.
public class BusinessData implements Business{
// Using an immutable collection to make data of report immutable
private final String name;
private final double commissionPerEmployee;
private List<Double> firstData;
private List<Double> secondData;
private List<Double> thirdData;
public BusinessData(String name,
double commissionPerEmployee,
double[] firstData,
double[] secondData,
double[] thirdData) {
this.name = name;
this.commissionPerEmployee = commissionPerEmployee;
if (firstData == null) {
this.firstData = null;
} else {
this.firstData = Collections.unmodifiableList(DoubleStream.of(firstData).boxed().collect(Collectors.toList()));;
}
if (secondData == null) {
this.secondData = null;
} else {
this.secondData = Collections.unmodifiableList(DoubleStream.of(secondData).boxed().collect(Collectors.toList()));;
}
if (thirdData == null) {
this.thirdData = null;
} else {
this.thirdData = Collections.unmodifiableList(DoubleStream.of(thirdData).boxed().collect(Collectors.toList()));;
}
}
#Override
public String getBusinessName() {
return name;
}
#Override
public double getIncome() {
return commissionPerEmployee;
}
#Override
public double[] getFirstData() {
if (firstData == null) {
return null;
} else {
return firstData.stream().mapToDouble(x -> x).toArray();
}
}
#Override
public double[] getSecondData() {
if (secondData == null) {
return null;
} else {
return secondData.stream().mapToDouble(x -> x).toArray();
}
}
#Override
public double[] getThirdData() {
if (thirdData == null) {
return null;
} else {
return thirdData.stream().mapToDouble(x -> x).toArray();
}
}
#Override
public boolean equals(Object object) {
if (object == null || getClass() != object.getClass()) {
return false;
}
Business that = (Business) object;
return Objects.equals(this.getBusinessName(), that.getBusinessName()) &&
Objects.equals(this.getIncome(), that.getIncome()) &&
Objects.equals(this.getFirstData(), that.getLegalData()) &&
Objects.equals(this.getSecondData(), that.getLegalData()) &&
Objects.equals(this.getThirdData(), that.getLegalData());
}
#Override
public int hashCode() {
return Objects.hash(name, commissionPerEmployee, firstData, secondData, thirdData);
}
}
I want specific object with all it's values by using it's unique id of object from object list.
I have tried but i am getting index -1 while running below code.
List<JobDataDetail> jobList = getJobList();
JobDataDetail object = jobList.get(jobList.indexOf(new JobDataDetail(jobReferenceId)));
from the class
public class JobDataDetail implements Serializable,Comparable<JobDataDetail> {
public int jobSequence;
public String jobReferenceId;
public String jobAddress;
public String jobScheduledDate;
public JobDataDetail() {
super();
// TODO Auto-generated constructor stub
}
public JobDataDetail(int jobSequence){
super();
this.jobSequence = jobSequence ;
}
public JobDataDetail(String jobReferenceId){
super();
this.jobReferenceId = jobReferenceId;
}
public int getJobSequence() {
return jobSequence;
}
public void setJobSequence(int jobSequence) {
this.jobSequence = jobSequence;
}
public String getJobReferenceId() {
return jobReferenceId;
}
public void setJobReferenceId(String jobReferenceId) {
this.jobReferenceId = jobReferenceId;
}
public String getJobAddress() {
return jobAddress;
}
public void setJobAddress(String jobAddress) {
this.jobAddress = jobAddress;
}
public String getJobScheduledDate() {
return jobScheduledDate;
}
public void setJobScheduledDate(String jobScheduledDate) {
this.jobScheduledDate = jobScheduledDate;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((jobReferenceId == null) ? 0 : jobReferenceId.hashCode());
result = prime * result + jobSequence;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JobDataDetail other = (JobDataDetail) obj;
if (jobReferenceId == null) {
if (other.jobReferenceId != null)
return false;
} else if (!jobReferenceId.equals(other.jobReferenceId))
return false;
if (jobSequence != other.jobSequence)
return false;
return true;
}
#Override
public int compareTo(JobDataDetail another) {
return this.getJobReferenceId().compareTo(another.getJobReferenceId());
}
}
List.indexOf() uses equals() method to compare objects.
In your case, you are assuming that two objects with same jobReferenceId are equals but your equals() method doesn't say so (because of the jobSequence test at the end of your method).
If you want to get an item from your list by one of its attribute, the easiest way would be using filter expression in Java 8:
JobDataDetail job = jobList.stream()
.filter(j -> j.getAttribute().equals(someValue))
.findFirst();
If Java 8 is not an option, I would go for a classic for loop iterating over the list.
I have removed jobSequence condition check from equals method and it's working.
In this Java class, note how use of the constructor has been disallowed and replaced with an interface driven builder that guides instantiation and does validation
public class Position implements Serializable {
private BigDecimal capital;
private BigDecimal tolerableRiskInPercentOfCapitalPerTrade;
private Direction direction;
private BigDecimal pricePerUnit;
private BigDecimal stopLossPricePerUnit;
private Position(){}
public final BigDecimal getTotalTolerableRiskPerTrade() {
return capital.multiply(tolerableRiskInPercentOfCapitalPerTrade.divide(new BigDecimal(100)));
}
public final BigDecimal getStopLossPerUnitLoss() {
if (direction.equals(Direction.LONG)){
return pricePerUnit.subtract(stopLossPricePerUnit);
} else {
return stopLossPricePerUnit.subtract(pricePerUnit);
}
}
public final BigDecimal getStopLossTotalLoss() {
return getStopLossPerUnitLoss().multiply(getUnitsToBuy());
}
public final BigDecimal getUnitsToBuy() {
BigDecimal result = getTotalTolerableRiskPerTrade().divide(getStopLossPerUnitLoss(), 0, BigDecimal.ROUND_DOWN);
if (capital.compareTo(result.multiply(pricePerUnit)) != 1){
return new BigDecimal(0);
} else {
return result;
}
}
public final BigDecimal getTotal() {
return getUnitsToBuy().multiply(pricePerUnit);
}
public static ICapital builder(){
return new Builder();
}
public interface ICapital {
ITolerableRiskInPercentOfCapitalPerTrade capital(final BigDecimal capital);
}
public interface ITolerableRiskInPercentOfCapitalPerTrade {
IDirection tolerableRiskInPercentOfCapitalPerTrade(final BigDecimal tolerableRiskInPercentOfCapitalPerTrade);
}
public interface IDirection {
IPricePerUnit direction(final Direction direction);
}
public interface IPricePerUnit {
IStopLossPricePerUnit pricePerUnit(final BigDecimal pricePerUnit);
}
public interface IStopLossPricePerUnit {
IBuild stopLossPricePerUnit(final BigDecimal stopLossPricePerUnit);
}
public interface IBuild {
Position build();
}
private static class Builder implements ICapital, ITolerableRiskInPercentOfCapitalPerTrade, IDirection, IPricePerUnit, IStopLossPricePerUnit, IBuild {
private final Position instance = new Position();
#Override
public Position build() {
return instance;
}
#Override
public ITolerableRiskInPercentOfCapitalPerTrade capital(final BigDecimal capital) {
basicValidate(capital);
instance.capital = capital;
return this;
}
#Override
public IDirection tolerableRiskInPercentOfCapitalPerTrade(final BigDecimal tolerableRiskInPercentOfCapitalPerTrade) {
basicValidate(tolerableRiskInPercentOfCapitalPerTrade);
if (tolerableRiskInPercentOfCapitalPerTrade.compareTo(new BigDecimal(100)) != -1) {
throw new IllegalArgumentException("riskInPercent must be lower than 100");
}
instance.tolerableRiskInPercentOfCapitalPerTrade = tolerableRiskInPercentOfCapitalPerTrade;
return this;
}
#Override
public IPricePerUnit direction(final Direction direction) {
if (direction==null) {
throw new IllegalArgumentException("argument can't be null");
}
instance.direction = direction;
return this;
}
#Override
public IStopLossPricePerUnit pricePerUnit(final BigDecimal pricePerUnit) {
basicValidate(pricePerUnit);
instance.pricePerUnit = pricePerUnit;
return this;
}
#Override
public IBuild stopLossPricePerUnit(final BigDecimal stopLossPricePerUnit) {
basicValidate(stopLossPricePerUnit);
if (instance.direction.equals(Direction.LONG) && instance.pricePerUnit.compareTo(stopLossPricePerUnit) != 1) {
throw new IllegalArgumentException("price must be higher than stopLossPrice");
}
if (instance.direction.equals(Direction.SHORT) && stopLossPricePerUnit.compareTo(instance.pricePerUnit) != 1) {
throw new IllegalArgumentException("stopLossPrice must be higher than price");
}
instance.stopLossPricePerUnit = stopLossPricePerUnit;
return this;
}
}
protected static void basicValidate(final BigDecimal bigDecimal) {
if (bigDecimal == null) {
throw new IllegalArgumentException("argument can't be null");
}
if (!(bigDecimal.signum() > 0)) {
throw new IllegalArgumentException("argument must have positive signum");
}
}
}
resulting in instantiation like this
Position.builder()
.capital(new BigDecimal(10000))
.tolerableRiskInPercentOfCapitalPerTrade(new BigDecimal(2))
.direction(Direction.LONG)
.pricePerUnit(new BigDecimal(25))
.stopLossPricePerUnit(new BigDecimal(24))
.build();
Trying to port code between languages isn't easy and identical functionality can't and shouldn't be expected. That said, are there any ways of emulating similar functionality in JavaScript? (vanilla or through some modules/libraries if necessary)
There are a few ways to do this.
One option is to do it almost exactly the same way: With a builder object that has methods to specify details and a build method (or similar) that you call to get the final object. The resulting call to build the object would look almost exactly the same (modulo type names and such).
Another option is to take advantage of JavaScript's object initializer syntax (aka "object literals") to have an "options" object that you pass into a constructor for the Position, like this:
function Position(options) {
if (/*...the options aren't valid...*/) {
throw new Error(/*...*/);
}
this.capital = options.capital;
// ...
}
Usage:
var p = new Position({
capital: 10000,
tolerableRiskInPercentOfCapitalPerTrade: 2,
direction: Direction.LONG,
pricePerUnit: 25,
stopLossPricePerUnit: 24
});
Inside the constructor, if you're going to use the data from options directly as properties on the new instance, you can use a function top copy them over:
function applyOptions(instance, options) {
Object.keys(options).forEach(function(key) {
instance[key] = options[key];
});
return instance;
}
Then:
function Position(options) {
if (/*...the options aren't valid...*/) {
throw new Error(/*...*/);
}
applyOptions(this, options);
}
(jQuery, if you use it, has an $.extend function that basically does this; Underscore, if you use it, has _.extend and _.extendOwn.)
But if you're going to be doing some manipulation of the options before storing them as properties on the new instance, a blind copy like that wouldn't be ideal.
Can anyone suggest me why the if condition is not working in the below code as the record has key as SiteId.
while (!pdsxOutRecords.isEmpty()) {
PdsxRecord record = pdsxOutRecords.remove(0);
// The below if condition is not working
if(record.getAttrs().containsKey("SiteId")) {
System.out.println("Testing");
}
}
And PdsxRecord class is like this
public class PdsxRecord
{
private String m_key;
private Map<PdsxAttrKey, PdsxAttrValue> m_mapAttrs;
}
// constructor
public PdsxRecord(String key, Map<PdsxAttrKey, PdsxAttrValue> mapAttrs)
{
m_key = key;
m_mapAttrs = mapAttrs;
}
public String getKey()
{
return m_key;
}
public Map<PdsxAttrKey, PdsxAttrValue> getAttrs()
{
return m_mapAttrs;
}
Below thing gets printed by using record.getAttrs()
{Gem.2036=null, Gem.2037=null, Gem.2038=com.ebay.pdsx.common.PdsxAttrValue#6b306b30, Gem.2039=null, Gem.10230=null, Gem.10117=null, Gem.10119=null, Gem.10240=null, UID=com.ebay.pdsx.common.PdsxAttrValue#1e501e50, Gem.10001=null, Gem.10002=com.ebay.pdsx.common.PdsxAttrValue#5d095d09, Gem.10003=null, Gem.10246=null, Gem.10247=null, Gem.60001=null, Gem.10007=null, Gem.10009=null, GEM_ROUTING.PartnerLastModifiedDate=null, Gem.70006=null, CGUID=com.ebay.pdsx.common.PdsxAttrValue#1e361e36, Gem.10173=null, Gem.10097=null, Gem.10131=null, Gem.10010=null, Gem.10132=null, Gem.10177=null, Gem.10178=null, Gem.10179=null, Gem.10015=null, TimeStamp=com.ebay.pdsx.common.PdsxAttrValue#1e571e57, Gem.10016=com.ebay.pdsx.common.PdsxAttrValue#645e645e, Gem.10018=null, Gem.10019=null, Gem.2025=null, SiteId=com.ebay.pdsx.common.PdsxAttrValue#1e3f1e3f, GEM_ROUTING.Partner1LastLoggedInUserId=null, GEM_ROUTING.Partner3LastLoggedInUserId=null, Gem.10181=null, Gem.10182=null, Gem.10183=null, Gem.10185=null, Gem.10187=null, Gem.10101=null, Gem.10189=null, Gem.10102=null, Gem.10026=null, PGuid=com.ebay.pdsx.common.PdsxAttrValue#1e461e46, Gem.2032=null, SGuid=null, Gem.2033=null, Gem.2034=null, Gem.2035=null}
This is the below PdsxRecord class
public class PdsxRecord
{
private String m_key;
private Map<PdsxAttrKey, PdsxAttrValue> m_mapAttrs;
// use the other constructor!
protected PdsxRecord()
{
}
// constructor
public PdsxRecord(String key, Map<PdsxAttrKey, PdsxAttrValue> mapAttrs)
{
m_key = key;
m_mapAttrs = mapAttrs;
}
/**
* get Key
*
* #return
*/
public String getKey()
{
return m_key;
}
/**
* get attributes as a map of key=value
*
* #return
*/
public Map<PdsxAttrKey, PdsxAttrValue> getAttrs()
{
return m_mapAttrs;
}
/**
* String -- for debugging and simple persistence
*/
public String toString()
{
UnsynchronizedStringBuffer buf = new UnsynchronizedStringBuffer();
buf.append("key=" + getKey() + "\n");
if (getAttrs() == null || getAttrs().size() == 0) {
return buf.toString();
}
for (Map.Entry<PdsxAttrKey, PdsxAttrValue> entry : getAttrs().entrySet()) {
String key = (entry.getKey()==null ? "null" : entry.getKey().getKey());
String value = ((entry.getValue() == null ||
entry.getValue().getValue() == null) ?
"null" : entry.getValue().getValue().toString());
buf.append(" " + key + "=" + value +"\n");
}
return buf.toString();
}
}
Updated:- Class for PdsxAttrKey
public class PdsxAttrKey
{
private String m_key;
protected PdsxAttrKey()
{
}
public PdsxAttrKey(String key)
{
m_key = key;
}
public String getKey()
{
return m_key;
}
/**
* Override the default to allow comparing with Strings
*/
public boolean equals(Object o)
{
if (o == null) {
return false;
}
if (o instanceof String) {
return o.equals(m_key);
}
if (o instanceof PdsxAttrKey) {
return m_key.equals(((PdsxAttrKey)o).getKey());
}
return false;
}
/**
* hash code implementation
*/
public int hashCode()
{
return (m_key == null ? 0 : m_key.hashCode());
}
public String toString()
{
return getKey();
}
}
Maybe because you Map is consisting of PdsxAttrKey as a key, and you are checking if there's a key which is a String with value "SiteId".
Here's some code that might be useful if you do not want to change your Map definition from Map<PdsxAttrKey, PdsxAttrValue> to something like Map<String, PdsxAttrValue>:
while (!pdsxOutRecords.isEmpty()) {
PdsxRecord record = pdsxOutRecords.remove(0);
if(record.getAttrs().containsKey(new PdsxAttrKey("SiteId"))) {
System.out.println("Testing");
}
}
Note that this assumes that you can pass a String to the PdsxAttrKey constructor, and that the class can be instantiated. Oh and of course that you have equals() and hashcode() in the class, which pretty much only check the String value for the of the PdsxAttrKey. You might ask yourself if this is really worth the hassle. That's why I originally suggested that your change your Map definition to use Strings as keys, but of course I am not sure if this is a viable solution in your case.
In record.getAttrs() you're returning: Map<PdsxAttrKey, PdsxAttrValue>. Then you checking if there is a key (type: PdsxAttrKey) of type String, value "SiteId".
You should check if map contains PdsxAttrKey (implementing equals and hashcode methods in PdsxAttrKey) or extracting keys from PdsxAttrKey and comparing them with "SiteId".
If you choose to iterate try this:
for(PdsxAttrKey key : record.getAttrs().keySet()) {
if("SiteId".equals(key.getYourKeyStringValue())) {
//found
break;
}
}
Otherwise you should implement equals and hashcode (remember - both) in PdsxAttrKey and invoke contains:
PdsxAttrKey lookupKey = new PdsxAttrKey("SiteId"); //with consideration of `equals` method
if(record.getAttrs().containsKey(lookupKey)) {
...
}
As Xeon says, if you want to compare object with string value, you must override equals and hascode method in the class which is used as key, in this case, PdsxAttrKey. As an example:
public class PdsxAttrKey {
public String name;
public PdsxAttrKey(String name) {
this.name = name;
}
#Override
public int hashCode() {
return name.hashCode();
}
#Override
public boolean equals(Object obj) {
if(obj == null) {
return false;
} else if (obj instanceof PdsxAttrKey) {
return this.name.equals(((PdsxAttrKey)obj).name);
}
return false;
}
}
Or If there is no real need to have an object as key, then you can redefine the map declaration as follows and use strings as key.
private Map<String, PdsxAttrValue> m_mapAttrs;