I have the following code snippet:
public List<EntityA> getAllEntityAByAAndDPaginated(
Collection<Long> a,
Collection<Long> d,
int numberOfResults,
int page
) {
TypedQuery<EntityA> q = entityManager.createNamedQuery(EntityA.GET_BY_A_AND_D,
EntityA.class);
q.setParameter(A, a);
q.setParameter(D, d);
q.setMaxResults((page + 1) * numberOfResults * d.size()); // without this, it works!
return a != null && !a.isEmpty() && d != null && !d.isEmpty()
? q.getResultList() : new ArrayList<>();
}
For performance reasons, I am only loading (page + 1) * numberOfResults * d.size() results. But executing this, I get a NullPointerException in the last line of the code snippet of the following form:
java.lang.NullPointerException
at java.base/java.util.ArrayList.<init>(ArrayList.java:179)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.prepareNestedJoinQueryClone(ForeignReferenceMapping.java:2455)
at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternalWithJoin(OneToOneMapping.java:1814)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:2177)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.buildCloneFromRow(ForeignReferenceMapping.java:341)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoWorkingCopyClone(ObjectBuilder.java:2007)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneFromRow(ObjectBuilder.java:2260)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:858)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:745)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:699)
at ...
According the exception stacktrace, it seems like it has tried somewhere to add null values to the result list. When I delete the part q.setMaxResults((page + 1) * numberOfResults * d.size());, it works fine, i.e. this has to cause the NPE somehow.
The database of EntityA does not contain any null values.
How can I fix this?
Related
UPDATE: Apologies for the confusion. All code MUST be written between the forward slashes i.e. the "//" beginning at the TO DO comment. And ends the line before the return answer.
Consequently this:
return price<20 ? "Buying new shirt" : null
is unfeasible as return answer is OUTSIDE the allowed code modification area.
I also didn't know if it was possible to assign a null object to a String object (as my comment indicated. And yes, I'm aware of the difference between "null" v null. That is the entire issue I'm having with the code failing to compile.
The ConditionalStatements() method is supposed to pass an integer input and return a string variable called answer.
If the passed integer price < 20 (to include negative integers), then the return variable answer = "Buying new shirt". Otherwise the compiler's expected return value for answer must be null i.e. the OBJECT null and NOT the string "null" which answer is initialized with.
Constraints:
if statement MUST be a Simple Conditional Statement with no branching.
cannot use catch try or other statements. Limited to use of compound conditionals and variables.
MUST be WITHIN the area designated by // forward slashes.
Because of this last constraint, I can't see a way to typecast/return the null as the test errors are indicating. Apologies again for the confusion.
I've tried short circuiting using && and the || operators. Tried getting creative with && and II operators in the if statement to make compound statements. e.g:
if ( (answer.equals(null) && (price >=20) ) etc.
to trap the incorrect test input and change answer data type. But compiler fails test cases of required answer = null for cases where price >= 20. Returning answer = "null" throws an error as a String object is returned v. the desired null.
How to type cast answer variable e.g. (null) answer = null; in my code below?
public class ConditionalStatements {
/**
* This method is used for problem one in the README.
* #param price A price that will be passed in by the test.
* #return String A string used to validate the test.
*/
public String simpleConditional(int price) {
String answer = "null";
**// TODO: Write Step 1 code between the forward slashes** <--start code modification area
(answer == null ) || (price < 20) )
answer = "Buying new shirt";
if( (price >= 20) ) {
answer = null; //this assignment is legal according to post feedback.
//However it STILL results in test failure message (shown in URLs below).
//Where the compiler is expecting a null object and not a string object....
//compiler won't accept answer = null; How to typecast answer String variable so it will accept null object?
}
// **<---this is the END of the code modification area**
return answer;
}
When compiler tries to compile, it fails with these test run errors:
All tests. Only price < 20 passed:
https://i.postimg.cc/TYrH051P/allTests.png
Test 3: price = 20, expected return for answer = null
https://i.postimg.cc/W3GJCVk0/Test3-err1.png
Test 4: price = 21, expected return for answer = null
https://i.postimg.cc/bNJsHk3x/Test4-err2.png
All you have to do assign null to answer variable, rather than "null" string. Check the below code, I think it does what you want to achieve.
public class ConditionalStatements {
/**
* This method is used for problem one in the README.
* #param price A price that will be passed in by the test.
* #return String A string used to validate the test.
*/
public String simpleConditional(int price) {
String answer = null;
// TODO: Write Step 1 code between the forward slashes (answer == null ) || (price < 20) )
if(price < 20){
answer = "Buying new shirt";
}
return answer;
}
public static void main(String[] args){
ConditionalStatements var = new ConditionalStatements();
System.out.println(var.simpleConditional(10)); // prints "Buying new shirt"
System.out.println(var.simpleConditional(25)); // return null object
}
}
To use null with explicit type you have to put a cast in front of null, in you example
if( (price >= 20) ) {
answer = (String) null;
}
I have an object that has operands and predicates inside.
I have the following model:
operand[0] - predicates = NULL
- operands[0] - predicates = NULL
- operands[0] - operands = NULL
- predicates[0] - tableVal="val1.aaa"
- predicates[1] - tableVal="val.bbb"
- predicates[2] = tableVal="val5.ccc"
- operands[1] - operands = NULL
- predicates[0] - tableVal="val3.asd"
- predicates[1] - tableVal="val2.ccc"
I'm looking for a certain value, that contains "bbb" and I need a recursive method to get through the whole structure until it finds the predicate with the tableVal containing "bbb".
I tried something like this:
private String searchInsideStructure(Object obj, int indexOperands) {
if (null != obj.predicates) {
indexPredicates = 0;
while(obj.predicates.length > indexPredicates) {
if(predicates[indexPredicates].tableVal.contains("bbb")) {
return tableVal;
}
indexPredicates++;
}
}
if (null != obj.operands) {
while (indexOperands < obj.operands.length) {
searchInsideStructure(obj.operands[indexOperands], indexOperands);
indexOperands++;
}
}
return null;
}
.................
indexOperands = 0;
searchedField = searchInsideStructure(initialObj, indexOperands);
if (null != searchedField) {
return searchedField
}
But it returns null. How can I change this recursive method to go through the operands, while finding predicates and finds in predicates the desired tableVal ("val.bbb" in this example)??? Thanks!
There's 2 fixes to consider:
In the second while loop, you should verify the result of searchInsideStructure, and propagate it if not null
You should avoid propagating indexOperands because it will make you skip some predicates when testing. You can then just use a for(each) loop to browse predicates.
Hello fellow coders,
I am writing a mod for Minecraft in 1.8 and have come across a pesky NullPointerException with my throwable. In the code below, the EntityThrowable uses an outer class to get the results of what will happen when thrown and the BlockPos passed is from the getBlockPos() method. This position is passed to the outer class where it transformed into x, y and z coords. However, whenever I throw the throwable, it throws an exception for these coordinates.
The difference between this question and the question of what is a NullPointerException is that the return value of what I am getting from the mov.getBlockPos() (from a MovingObjectPosition) is unknown. The MovingObjectPosition assigns the coords of the BlockPos from a random class and the coder of the Throwable gets the results. I am using the results for the outer class. These results in the ints cause the game to crash from unknown coords. If you have any idea of how to get the end pos of the throwable, that would be appreciated.
Here's the code:
Throwable:
#Override
protected void onImpact(MovingObjectPosition mov) {
LuckyPotionItems lpi = new LuckyPotionItems();
EntityPlayer player = this.getThrower() instanceof EntityPlayer ? (EntityPlayer) this.getThrower() : null;
if(!worldObj.isRemote)
lpi.chooseUnluckyDrink(worldObj, player, mov.getBlockPos());
this.setDead();
}
Outer Class:
public void chooseUnluckyDrink(World w, EntityPlayer p, BlockPos pos){
Random r = w.rand;
int number = r.nextInt(13);
int x = pos.getX();
int y = pos.getY();
int z = pos.getZ();
System.out.println("Unlucky Number = " + number);
Thanks for any help.
It sounds like the problem could be solved by checking if the BlockPos and the EntityPlayer are not null. If they aren't null, then run the method. If they are null, simply prevent the method from being ran.
#Override
protected void onImpact(MovingObjectPosition mov) {
LuckyPotionItems lpi = new LuckyPotionItems();
EntityPlayer player = this.getThrower() instanceof EntityPlayer ? (EntityPlayer) this.getThrower() : null;
if(mov.getBlockPos() != null && player != null) {
if(!worldObj.isRemote)
lpi.chooseUnluckyDrink(worldObj, player, mov.getBlockPos());
this.setDead();
}
}
number = (number == null) ? "" : number;
System.out.println("Unlucky Number = " + number);
int x = (pos.getX() == null ) ? 0 : pos.getX();
you are getting a null value for the number which means there is no output in r.nextInt(13); you need to fix that. Im using a conditional statement to check the value of number if its null then it will assign a value for number which can then be printed. try with my example this would help you.
I am new to programming and have a simple question: is there a "better" or more efficient way of doing this...
if (x != 0) {
y = x;
}
or
if (getMethod() != null) {
value = getMethod();
}
I'm new to programming and above code (esp the 2nd one) seems inefficient.
Thanks in advance.
You second example can suffer from a "Time of check, to time of use" weakness. If the first invocation of getMethod() returns non-null, it is possible that your second invocation will return null. A better way to do it would be:
value = getMethod();
if(NULL != value)
{
/* use value as planned */
}
else
{
/* handle a null value, probably an error */
}
if interested, you can read more about TOCTTOU weaknesses here.
For your first example, I don't really see a better way of doing this.
N.B. This answer is from the perspective of a C programmer (seeing as how C was one of your tags).
Hope this helps
- T.
You can make it shorter
if ( x ) y = x;
is the same as
if (x != 0) {
y = x;
}
And
if ( getMethod() ) value = getMethod();
is the same as
if (getMethod() != null) {
value = getMethod();
}
First code snippet:
In C any non-zero value is treated as true and 0 treated as false. So, for the first example, you can rewrite it as:
if (x) {
y = x; // this line will be executed if x not equal to zero
}
Second code snippet:
You called getMethod() twice which is not efficient. As per your code, you are assigning the return value of getMethod() into value if getMethod() returns anything but NULL. So you can use a temporary variable to check the return value of getMethod(), like following:
temp = getMethod();
if (temp != null) {
value = temp;
}
That will reduce calling same method twice.
Hi
I have written such this code but it will return this exception .and I do not know why please help me thanks.
private void Scan(DoublyLinkedList dList) { // T(n) = O(n)
DNode p1 = dList.getFirst();
while (p1!=null) {
DNode p2 = p1.next;
System.out.println(p1.getElement().toString()+"lol");
if (p2.next!=null) {
DNode p3 = p2.next;
if(p3.getElement()!=null){
boolean b = Determinate.isPointRightSide(p1.getElement(), p2.getElement(),p3.getElement());
if (b == true) {
p1 = p1.next;
} else {
p1.next = p3;
p3.prev = p1;
dList.remove(p2);
p1 = p1.prev;
}
}
else break;
}else break;}
}
public static double determinate(Object get, Object get0, Object get1) {
double data[][] = new double[3][2];
data[0][0] = ((Point) get).getX();
data[0][1] = ((Point) get).getY();
data[1][0] = ((Point) get0).getX();
data[1][1] = ((Point) get0).getY();
**data[2][0] = ((Point) get1).getX();**
data[2][1] = ((Point) get1).getY();
return ((data[0][0] * (data[1][1] - data[2][1])) - (data[1][0] * (data[0][1] - data[2][1])) + (data[2][0] * (data[0][1] - data[1][1])));
}
exception:
run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ConvexHull.Determinate.determinate(Determinate.java:55)
at ConvexHull.Determinate.isPointRightSide(Determinate.java:15)
at ConvexHull.GrahamVersion.Scan(GrahamVersion.java:104)
at ConvexHull.GrahamVersion.grahamScan(GrahamVersion.java:83)
at ConvexHull.GrahamVersion.<init>(GrahamVersion.java:25)
at UI.MainFrame.grahamButtonActionPerformed(MainFrame.java:221)
this will show that "p3" is null! but I have check "p3" why it returns "null" again?
I use strong for showing those lines that throws exception.
EDIT: Ihave edited my post but it will throw this exception for "p1"
One thing that looks wrong is:
if (!p3.equals(null))
This will generally always be true (if p3 != null) or throw a NullPointerException (if p3 == null)
The correct way to test whether p3 is not null is:
if (p3 != null)
Although that may not be why you're getting your NullPointerException
If the NullPointerException occurs on the line you highlight, it must be because get1 is null. This is passed in as p3.getElement(), so find out whether that could be null.
In theory, if data[2] was null then data[2][0] would throw a NullPointerException but since you initialize data then that won't be the problem in this case.
Also, is there some reason that your parameters for determinate() are Object instead of Point? If this is your actual code and not some simplified test-case, then the parameters should all be Point since that's what they must be.
Edit:
I see you've changed your original code to add some of the suggestions on this page.
But I still see some problems:
while (p1!=null) {
DNode p2 = p1.next;
if (p2.next!=null) {
// ^^^^^^^ If p2 is null, then this will throw NullPointerException
DNode p3 = p2.next;
if(p3.getElement()!=null){
// ^^^^^^^^^^^^^^^ If p3 is null, then this will throw NullPointerException
boolean b = Determinate.isPointRightSide(p1.getElement(), p2.getElement(),p3.getElement());
// ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ if one of these returns null then isPointRightSide() will throw a NullPointerException
I'm pretty sure you got the wrong line, because this:
!p3.equals(null)
will not work - that line (or those involving p1 or p2) is throwing the Exception. You cannot invoke any method on a null, including equals(). Use this instead for all your null checks:
p3 != null