我需要在这个公式[i]中创建一个空检查,我不完全确定如何解决这个问题,因为我不太熟悉null检查和编程方面的新功能.任何和所有的帮助非常感谢!
public static double calculateInventoryTotal(Book[] books)
{
double total = 0;
for (int i = 0; i < books.length; i++)
{
total += books[i].getPrice();
}
return total;
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
为什么检查这个!= null?
// Determines whether two strings match.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(Object obj)
{
//this is necessary to guard against reverse-pinvokes and
//other callers who do not use the callvirt instruction
if (this == null)
throw new NullReferenceException();
String str = obj as String;
if (str == null)
return false;
if (Object.ReferenceEquals(this, obj))
return true;
return EqualsHelper(this, str);
}
Run Code Online (Sandbox Code Playgroud)
我不理解的部分是它正在检查当前实例,this而不是null.评论有点令人困惑,所以我想知道这个评论究竟意味着什么?
任何人都可以给出一个例子,说明如果那个检查不存在,这可能会破坏,这是否意味着我还应该将检查放在我的课程中?
我正在编写一个实用程序方法,可以检查空字符串和空字符串,或集合或对象或任何常规类型 -
public static boolean isEmpty(Object obj) {
if (obj == null)
return true;
if (obj instanceof Collection)
return ((Collection<?>) obj).size() == 0;
// is below line expensive?
final String s = String.valueOf(obj).trim();
return s.length() == 0 || s.equalsIgnoreCase("null");
}
Run Code Online (Sandbox Code Playgroud)
如何使上述方法高效,因为上述isEmpty方法将从应用程序中多次调用,这对性能至关重要?
我怀疑下面的行是昂贵的,因为繁重的toString方法,它会创建临时垃圾,可能会导致GC并降低性能?
final String s = String.valueOf(obj).trim();
Run Code Online (Sandbox Code Playgroud)
更新: -
我现在为每种类型分离了isEmpty方法.以下是我在简化上述isEmpty方法后得到的结果.
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
return false;
}
public static boolean isEmpty(Collection<?> value) {
if (value == null || …Run Code Online (Sandbox Code Playgroud) 在你急于思考之前?null合并运算符:
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
Run Code Online (Sandbox Code Playgroud)
这里的问题是当myParent或objProperty为null时,它会在达到strProperty的评估之前抛出异常.
要避免以下额外的空检查:
if (myParent != null)
{
if (objProperty!= null)
{
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
}
}
Run Code Online (Sandbox Code Playgroud)
我通常使用这样的东西:
string result = ((myParent ?? new ParentClass())
.objProperty ?? new ObjPropertyClass())
.strProperty ?? "default string value if strObjProperty is null";
Run Code Online (Sandbox Code Playgroud)
因此,如果对象为null,则它只创建一个新对象才能访问该属性.
哪个不是很干净.
我想要一个像'???'的东西 运营商:
string result = (myParent.objProperty.strProperty) ??? "default string value if strObjProperty is null";
Run Code Online (Sandbox Code Playgroud)
...它将从括号内的任何"null"中存活,以返回默认值.
谢谢你的提示.
我使用时遇到问题AnimatedSplashScreen,在我添加pageTransitionType. 然后我得到一个错误:
\n\n构建 AnimatedBuilder(animation: Listenable.merge([kAlwaysCompleteAnimation\xe2\x9e\xa9ProxyAnimation, kAlwaysDismissedAnimation\xe2\x9e\xa9ProxyAnimation]), dirty, state: _AnimatedState#bd6f7):\n在 null 上使用 Null 检查运算符时抛出以下 _CastError价值
\n
这是一个产生该问题的简单应用程序:
\nimport \'package:animated_splash_screen/animated_splash_screen.dart\';\nimport \'package:flutter/material.dart\';\nimport \'package:page_transition/page_transition.dart\';\n\nvoid main() {\n runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n home: AnimatedSplashScreen(\n splash: Icon(Icons.person),\n pageTransitionType: PageTransitionType.scale, //with that line commented there is no error\n nextScreen: HomePage()\n ),\n );\n }\n}\n\nclass HomePage extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return Container();\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n我尝试过运行许多命令,例如flutter pub get等。
\n …我试图对字符串进行空检查,但它不起作用。
<s:iterator value="matrix" var="row">
<tr>
<s:iterator value="value" var="col">
<td>
<s:if test="%{#col==null}">0</s:if>
<s:else><s:property value="col"/></s:else>
</td>
</s:iterator>
</tr>
</s:iterator>
Run Code Online (Sandbox Code Playgroud)
矩阵是一个
Map<Integer, List<String>>
Run Code Online (Sandbox Code Playgroud)
var“col”已正确分配列表中的字符串值。
该列表可能如下所示 [ "hello" , null , "world ]
当前输出:hello world
想要的输出:hello 0 world
/提前致谢
我在使用Oracle java 8u25的Windows 7 64位上的Spring工具套件3.6.2(Eclipse clon)下遇到了奇怪的nullcheck分析行为.与java 7源兼容性相同的maven项目在eclipse中成功找到NPE错误,但是当我将maven中的编译版本更改为java 1.8时,eclipse无法找到此错误.
我在Eclipse中的nullcheck分析配置(Java-> Compiler-> Errors/Warnings-> Null分析)是:在null分析中包含断言true启用基于注释的分析true NotNull自定义注释正确设置为javax.validation.constraints.NotNull等. (一切似乎没问题,因为它在java 7下工作)
我的maven pom在这里http://pastebin.com/pF1yJSG2,如上所述当pom中的java.version是1.7 null检查工作时,当1.8为空时检查不起作用.
示例源代码是:
package test.nullcheckbug.core;
import javax.validation.constraints.NotNull;
public class Program {
/**
* This will fail to compile under java 7 (null analysis works in STS
* 3.6.2). But under java 8 it does not show error in Eclipse Markers -
* static analysis does not work ?!
*
* @return null which is not allowed
*/
@NotNull
public String fail() { …Run Code Online (Sandbox Code Playgroud) 当我编码时,我对空检查感到沮丧.特别是在编码数据结构时!
我必须这样做
String val;
if(a != null && a.child != null)
val = a.child.getValue();
else
val = null;
Run Code Online (Sandbox Code Playgroud)
这有点......
有运营商吗?(这是C#的一部分)让Java缩短负担?
С#例子:
String val = a?.child?.getValue();
Run Code Online (Sandbox Code Playgroud) 我正在使用RPC(protobuf-remote),我需要做一些检查以防另一端(服务器)关闭.假设我有很多RPC方法,比如:
public FirstObj First(string one, string two)
{
if (rpc == null)
return (FirstObj)Activator.CreateInstance(typeof(FirstObj));
return rpc.First(one, two);
}
public SecondObj Second(string one)
{
if (rpc == null)
return (SecondObj)Activator.CreateInstance(typeof(SecondObj));
return rpc.Second(one);
}
public ThirdObj Third()
{
if (rpc == null)
return (ThirdObj)Activator.CreateInstance(typeof(ThirdObj));
return rpc.Third();
}
Run Code Online (Sandbox Code Playgroud)
反正有没有改变这个重复的空检查代码?所以我可以这样写:
public FirstObj First(string one, string two)
{
return rpc.First(one, two);
}
Run Code Online (Sandbox Code Playgroud)
哪个会进行空检查,如果RPC服务器关闭,它会按类型创建对象,所以我将得到所需对象的默认值.
我得到了一个neighbor数组(由 Tile 对象组成),它的长度始终为 4,无论是否填充了所有元素。如果该元素/位置不为空,我想扫描该数组并更改 Tile 中包含的 PB 的颜色。我可以if neighbors[i] = null使用以下代码通过标准检查来做到这一点:
for (int i = 0; i < Neighbors.Count(); i++)
{
if (Neighbors[i] != null)
Neighbors[i].TilePB.Backcolor = Color.Red;
else
continue; // just put that here for some more context.
}
Run Code Online (Sandbox Code Playgroud)
但我想知道是否可以在一行中完成此操作,类似于使用 ? 操作员。我试过使用三元运算符,但我不能continue使用一个(我尝试过的三元语句:Neighbors[i] != null ? /* do something */ : continue,为什么它不起作用的来源:为什么 break 不能与三元运算符一起使用?)。
是否有另一种方法来检查数组的元素是否为空,只使用一行(最好不使用 hack)?