为什么要把比较的字符放在前面(java2)

答:为了减少空指针异常的产生。

一般情况下把比较的字符放在后面,因为这样更符合我们的阅读理解和标准,像下面的代码:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Test {
	public static void main(String[] args) {
		//定义一个collection集合		
		Collection<String> c = new ArrayList<String>();
		//随便向集合添加几个元素		
		c.add("我");
		c.add("#");
		c.add("爱");
		c.add("#");
		c.add("北京");
		c.add("#");
		c.add("天安门");
		//使用迭代器便利集合		
		Iterator it = c.iterator();
		//遵循问,取,删的模式来便利集合,删除不是必须的哦
		while (it.hasNext()) {
			String str = (String) it.next();
			//把字符是"#"的字符删除,第一次先把被比较的字符放在后面
			if(str.equals("#")){
				it.remove();
			}
		}
		System.out.println(c);
	}
}

运行程序:

输出结果是:

[我, 爱, 北京, 天安门]

但是如果像集合中添加一个空元素:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Test {
	public static void main(String[] args) {
		//定义一个collection集合		
		Collection<String> c = new ArrayList<String>();
		//向集合添加有个空值
		c.add(null);
		c.add("我");
		c.add("#");
		c.add("爱");
		c.add("#");
		c.add("北京");
		c.add("#");
		c.add("天安门");
		//使用迭代器便利集合		
		Iterator it = c.iterator();
		//遵循问,取,删的模式来便利集合,删除不是必须的哦
		while (it.hasNext()) {
			String str = (String) it.next();
			//把字符是"#"的字符删除
			if(str.equals("#")){
				it.remove();
			}
		}
		System.out.println(c);
	}
}

这时在运行程序,会发现程序发生空指针异常,结果如下:

Exception in thread "main" java.lang.NullPointerException

但是如果在字符比较的时候把被比较的字符放在前面,下面的代码:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Test {
	public static void main(String[] args) {
		//定义一个collection集合		
		Collection<String> c = new ArrayList<String>();
		//向集合添加有个空值
		c.add(null);
		c.add("我");
		c.add("#");
		c.add("爱");
		c.add("#");
		c.add("北京");
		c.add("#");
		c.add("天安门");
		//使用迭代器便利集合		
		Iterator it = c.iterator();
		//遵循问,取,删的模式来便利集合,删除不是必须的哦
		while (it.hasNext()) {
			String str = (String) it.next();
			//把字符是"#"的字符删除,把被比较的字符放在前面
			if("#".equals(str)){
				it.remove();
			}
		}
		System.out.println(c);
	}
}

程序正常运行,结果如下:

[null, 我, 爱, 北京, 天安门]

综上所述,一个小小的习惯可以避免一种异常的习惯。。。

---------------------------------------------------------(又是这条很有教养的分界线)

欢迎大家在下方留言和指正,主题有一个小BUG,不用多次点击发表评论按钮。。。。

 

 

打赏
点赞
  1. Darcel Roary说道:

    I just could not leave your site prior to suggesting that I extremely loved the standard info a person supply to your visitors? Is gonna be back incessantly in order to inspect new posts

  2. zvodretiluret说道:

    Enjoyed reading through this, very good stuff, thanks.

  3. Kimberly说道:

    An estate agents viagra for diabetes erectile dysfunction Beside the top OMB job, Zients was also considered for twoCabinet posts, secretary of commerce and U.S. traderepresentative, but those jobs went to Penny Pritzker, abusinesswoman from Chicago and top Obama fundraiser, and MikeFroman, a White House adviser on international economics,respectively.

  4. Dustin说道:

    I want to report a is it good to take viagra when your 18 “There is a clear recognition of the importance of exploring alternative methods for educational delivery, but to date very few not-for-profit colleges and universities have radically changed their business model,” said Gagnon, who also serves as KPMG’s Northeast Area leader for higher education and not-for-profits. “Institutions that can strike the appropriate balance between on-campus and online experiences will be most successful.”

  5. Grant说道:

    I’m on work experience is viagra a prescription drug in thailand But the Cashman comment that made me believe the Yankees are not going to haggle with Girardi — and will instead attempt to get to a dollar figure that secures him quickly — had nothing directly to do with Girardi: “We have a lot of work to do.”

  6. Loren说道:

    I’m interested in viagra naturale “10 hours have passed and the Mujahideen are still strong inside #Westgate Mall and still holding their ground. All praise is due to Allah!”, the group said late on Saturday, although its account on Twitter was suspended on Sunday morning.

  7. Dillon说道:

    We’re at university together what mg viagra should i take After typical maintenance and forced power-plant outagestotaling 5,600 MW, ERCOT said it would expect to have more than20,000 MW of available capacity. Extreme weather or extremegeneration outages could reduce that reserve.

  8. Scotty说道:

    Very funny pictures where to order viagra I think the headline writer got it backward. A merged airline COULD offer more, WOULD charge more. Ever since the demise of the CAB in 1979-80 timeframe, airlines have been consolidating and giving much less for a higher cost to passengers. This natural penchant of big business to extract as much from customers as possible while giving them less and les is a natural phenomenon. Don’t forget that the e-mail and internal airline evidence DOJ is using in its suit to block the AA/US merger indicated that its chief aim is to position itself to charge more and higher fares and fees. Almost nothing but a seat is included in the ticket cost anymore. Why would it be unrealistic to expect a traveler to need luggage, sometimes that must be checked? Sure, a meal is nice, though unnecessary, but to gouge clients for traveling with supplies for their travels? Shameless.

  9. Mitchel说道:

    What sort of music do you listen to? viagra vancouver craigslist “Notwithstanding some volatility that we’ve seen in the lastsix weeks, speaking now and explaining what we’re doing may haveavoided a much more difficult situation at another time,”Bernanke said at an economics conference last Wednesday, hisfirst public remarks since the Fed’s June 19 policy meeting.

  10. Dennis说道:

    I’m doing a masters in law buy viagra online perth australia Some savers face losing more than 80pc of their previous return. For example, Nottingham BS has cut its eSaver Instant issue 1 rate from 2.62pc to 0.50pc – a drop of 2.12 percentage points. The mutual also cut its eSaver Instant issue 2 by 1.85 percentage points.

  11. Lamar说道:

    An accountancy practice can you take viagra at night The prisoner accused of shooting a sheriff’s deputy at the Massachusetts Eye and Ear Infirmary last week was arraigned in his hospital bed at Massachusetts General Hospital this afternoon and ordered held on $1 million cash bail.

  12. Kasey说道:

    Where are you calling from? does cvs sell viagra over the counter LB Dan Connor (neck) was placed on IR and that really affects the Giants’ flexibility in coverage. Mark Herzlich will now match wits with Peyton Manning. CB Prince Amukamara (concussion) is trying to get on the field. That would leave Terrell Thomas in the slot against Wes Welker . The Giants should get C David Baas back from a knee injury. He’s practiced all week. CB Champ Bailey , who injured his foot in the preseason, will miss his second game. MLB Wesley Woodyard (ankle) will play after missing some practice time. Pass rusher Von Miller remains suspended.

  13. Chauncey说道:

    I’m from England cialis viagra levitra samples Some helpful information to pass along to these sources are the price the goods are selling for, if they are being sold in multiple quantities, any brand names on the product, as well as the date and seller information. If you spotted these goods online, Biggs recommends taking a screenshot of the product, and sharing the web address when reporting the claim. Biggs also adds that most customers will be able to remain anonymous when sharing these tips with local police task forces and companies.

  14. Willian说道:

    Looking for a job how much does a prescription of viagra cost without insurance It doesn’t change that right here and right now this is all the chance they could have wanted, all the season they could have wanted. Now they have to do something about that. The Giants needed one lousy win the other night? The Jets need to win two games in a row.

  15. Gustavo说道:

    The manager overnight viagra “For Alex Salmond to treat us like fools by deliberately confusing the wholesale value of oil with the amount we would actually raise through tax is fundamentally dishonest. He should withdraw the claim.”

  16. Byron说道:

    US dollars can viagra be taken with high blood pressure medication SPD leaders must take care not to appear overly eager for adeal with Merkel given deep scepticism among the party’s rankand file. On Sunday, 200 senior SPD members will vote on whetherto continue coalition talks, and any final decision on forming anew government will be put to a vote by the party’s 472,000members.

  17. Jayson说道:

    Just over two years 50 mg viagra did not work After the weekend raid to detain al-Liby,a suspected al-Qaeda operative wanted for his alleged involvement in the 1998 bombings of two US embassies in Africa, militant groups took to social networking sites to call for revenge attacks on strategic targets including gas pipelines and shipping.

  18. Isreal说道:

    Can I call you back? actual shelf life of viagra Smith, despite a reputation for mobility, was generally a poor rusher in college. He averaged just 1.4 yards on 245 carries in his career at West Virginia, but has looked effective in his few attempts with the Jets.

  19. Timothy说道:

    Languages prirodna viagra za zene TOKYO — Japan once again has become without atomic energy as its only operating nuclear reactor went offline Sunday for refueling and maintenance, and other plants remain closed for intensified safety checks following the 2011 meltdowns at the tsunami-stricken plant in Fukushima.

  20. Brendan说道:

    I’ve been made redundant generic viagra south africa An awful lot of people are saying that they don’t mind if their emails, Skype calls and mobile phone records are being collected. If that helps the state to protect them and their families, it’s OK.

  21. Alberto说道:

    Canada>Canada viagra at cvs price “They race too fast, I think. I think in time they will think differently, because they will learn if you are fastest from the start you are not so often first across the line,” said Werder. “It’s better to sit back and wait.”

  22. Xavier说道:

    Could I borrow your phone, please? viagra for sales in houston tx Some market participants believe that if Batista were to walk away from OGX, it would ease tensions in talks with bondholders and potentially facilitate a resolution that could save the company from bankruptcy.

  23. Robby说道:

    Whereabouts are you from? indian viagra 50mg That means revenues should be raised from the wealthy, who have never been wealthier — limiting their deductions and tax credits, closing loopholes like “carried interest,” and taxing financial transactions. Spending should be cut by ending corporate welfare — terminating tax subsidies to oil and gas, ballooning payments to agribusiness, sweetheart deals for military contractors, and the “too big to fail” subsidy for Wall Street’s biggest banks. Future health-care costs should be contained by using the government’s bargaining leverage over providers (through Medicare, Medicaid, and the Affordable Care Act) to force a shift from fee-for-service to payments-for-healthy-outcomes. And we should spend more on high-quality education and infrastructure for everyone.

  24. Noble说道:

    A law firm how much does viagra cost in uk “She said she believed in him and his policies. She said he has the light people need to look at and respond to,” Perry said. “It was a gathering of people who felt he could make a difference in Washington.”

  25. Isabel说道:

    Good crew it’s cool :) where is the best place to order viagra online O2 was least likely to provide a speed range, supplying this in 58 per cent of calls. Talk Talk (47 per cent of calls) and O2 (55 per cent) were the least likely to provide an unprompted speed estimate.

  26. Magic说道:

    What do you do? best place to buy generic viagra online reviews It takes just under 3 days and $3,460 to move a 40-foot container from Mexico to the United States, compared to nearly 21 days and $4,665 to move the same cargo from China, according to A.T.Kearney, a consulting firm.

  27. Jamar说道:

    I want to make a withdrawal 50 mg viagra vs 100mg viagra The $9 a share tentative offer, from a consortium led by property and casualty insurer Fairfax Financial Holdings Ltd, will set a floor for any counteroffers that might emerge for Blackberry, which has been on the block since August.

  28. Oswaldo说道:

    I’m happy very good site viagra jellies Among the other attendees of the hastily arranged meeting were Amnesty International Russia Chief Sergei Nikitin, Human Rights Watch worker Tanya Lokshina and Russian human rights ombudsman Vladimir Lukin.

  29. Marvin说道:

    good material thanks does viagra help you stay hard after ejaculation Actor Barry Williams, who played oldest son Greg Brady, has spoken publicly about his crush on his TV mom Florence Henderson—a.k.a Carol. But the romance didn’t end there. Williams took Henderson out on a date when he was 15 and she was 36. At the end of the night, the costars shared an innocent kiss on the lips.

  30. Nigel说道:

    I’ve been made redundant can you buy viagra over the counter in spain “This decision completely contradicts David Cameron's belief that farmers are the backbone of Britain and the recommendations of the Migrant Advisory Committee that horticulture would suffer immeasurably without access to a reliable, flexible and consistent source of migrant seasonal workers.”

  31. Federico说道:

    How long are you planning to stay here? viagra online canadian no prescription The deal is likely to lead to the sale or partial sale of Telecom Italia’s treasured Brazilian unit Tim Participacoes, worth $10 billion on the market, as the increased Telefonica stake will likely generate antitrust problems.

  32. Michale说道:

    What do you do? do you need a prescription to buy viagra in ireland The cameras are always rolling in Hollywood! When the stars aren’t on the red carpet, you’ll more than likely find them on set filming their next great blockbuster. Check out these famous actors and a…

  33. Lance说道:

    real beauty page viagra side effects heart condition Listen to Tom Coughlin at his Friday press conference, when he talked about all the reasons why the Giants are where they are. Here is Coughlin talking about Rueben Randle breaking off his pattern and taking off when he saw the Bears cornerback sitting on his pass route, a play that soon became 7-0 for the Bears.

  34. Shaun说道:

    I wanted to live abroad viagra c20 Despite the threat of strike action from delivery staff and criticism from opposition lawmakers, the government is close to completing the sale of a majority stake in the near 500-year-old Royal Mail – the fourth attempt to sell off the postal service.

  35. Eli说道:

    I work for myself viagra description As for the father of the 17-year-old who placed the original winning bid, however, we suspect he’s no longer as speechless as he was when he first heard the news. In an apologetic email sent to Bahnhof on Thursday, he said he had yet to properly discuss the matter with the teen, but that “A more serious conversation will be tomorrow.” ®

  36. Johnathon说道:

    I’m unemployed how long should i wait to take viagra after eating Volkswagen commends the Insurance Institute for Highway Safety’s (IIHS) efforts to improve the safety of all vehicles on the roads of America. This latest test—the small overlap test in which 25 percent of a vehicle’s front end strikes a five-foot tall barrier at 40 mph—is further evidence of the IIHS’s commitment to vehicle safety.

  37. Heath说道:

    International directory enquiries kamagra gel vs viagra In the time I’ve been here, all of the following have happened. Kevin Rudd ­ the prime minister, has posted a self-portrait of a shaving cut on Twitter. The papers have reported as news the fact that Mr Abbott once said “suppository” when he meant “repository”, as if this signifies anything beyond the odd difficulty one might have with five-syllable words when one has been talking all day on little sleep. Both Mr Rudd and Mr Abbott have recorded special messages for the participants in the current Australian series of “Big Brother”. None of which is even to speak of the motley riot of yahoos and grandstanders seeking election to the Senate from the fringes, several of whom make Julian Assange’s run from his camp bed in the Ecuadorian embassy in London look a model of plausibility.

  38. Luis说道:

    An envelope viagra barato online Greenpeace said to honor his promise, Hollande would have to close at least 10 reactors by 2017 and 20 by 2020. The campaign group said this ought to include Tricastin, which was built over 30 years ago.

  39. Christian说道:

    A Second Class stamp over the counter medicine similar to viagra Love was in the air at the AW13 Burberry show earlier this year, as they showcased one of the leading trends for the coming season. From shirts and dresses, to dainty gloves and hidden high waisted knickers, it was clear that feminine heart prints were set to dominate by the end of the year. Plus, when Victoria Beckham AND heart-throb Harry Styles don a trend, you know it's going to be big.

  40. Fernando说道:

    I’m on a course at the moment cumpar viagra cialis “Obviously, this is going to be the new age of monarchy. I mean, this young child may not even inherit the throne until the 22nd century. In fact, the great majority of us won’t see this baby actually become monarch, and we’re looking at quite far into the future. However, this baby – and, you know, this young royal couple – will, undoubtedly, be the focus of media attention, you know; they are this kind of celebrity couple; they are the, sort of, glamorous face of the British monarchy: their image is going to be hugely exported around the world.”

  41. Brock说道:

    How do you know each other? viagra tablets price in hyderabad After two games in Europe, the third was played on a college campus. The team bus left Philadelphia around 3:30, but the rain and traffic turned a 45-minute trip into one of almost 2 hours. There hasn’t been a lot of normalcy surrounding Brown’s team so far, but he doesn’t see it as a detriment.

  42. Geoffrey说道:

    I’ve only just arrived do u need a prescription for viagra in south africa Robert Dziak, the lead author of the study and a marine geologist, explained that in one hour-long period, the sound energy released by the iceberg melting was equivalent to the sound of a few hundred supertankers over the same period. Referring to the sounds as “icequakes,” the rapid melting of the iceberg caused the sound, much like the process and ensuing sounds of an earthquake.

  43. Leroy说道:

    Children with disabilities herbal viagra alternative new zealand That has also been shown in lab studies, Baron says. It’s not clear why people with insomnia don’t get the same immediate benefits. But, she says, “It probably has to do with the underlying reasons they have insomnia.”

  44. Billy说道:

    It’s a bad line medicare part d viagra However, the Saudis struck a $29.4 billion deal only in late 2011 to buy 84 new F-15s made by Boeing with Raytheon Co radar equipment. In November they also agreed to buy 25 C-130J transport and refueling planes built by Lockheed Martin Corp for $6.7 billion.

  45. Evelyn说道:

    I’d like a phonecard, please viagra will generic Another source familiar with the matter played down thedifficulty of selling Schneider’s shares in the event itsproposal succeeds, pointing out that the stock element of itsproposal equates to less than 5 percent of the French group’smarket capitalisation and that its shares are very liquid.

  46. Tracey说道:

    I went to viagra indiano “Funny enough, for a minute I thought I was getting pre-menopausal because certain things were starting to be irregular and then other symptoms started — my memory, and I was clumsier than normal which, I couldn’t even believe was possible,” she told the audience.

  47. Emily说道:

    Could I borrow your phone, please? viagra online purchase in india There have also been reports of violent protests in Hell-Ville, the main city on Nosy Be island also known as Andoany, though the situation is now calm, the US Embassy said in an emergency message to its citizens.

  48. Dirtbill说道:

    I’m only getting an answering machine testpackung viagra cialis The hope is that the young nucleus can generate enough heat on quarterbacks to relieve the burden on a revamped secondary, but Ryan still needs help from his edge pass rushers. Coples will play more on the edge, but his role as an outside linebacker has been greatly exaggerated. He’ll see his fair share of time as an interior pass rusher again.

  49. Houston说道:

    What’s the interest rate on this account? where can i buy female viagra in the uk They raised doubts about the nature of the petroleum cargoon the runaway train, which was listed as hauling 50,000 barrelsof crude oil when it derailed and smashed into the center of thesmall lakeside town near the Maine border, exploding in a blastthat killed 47 people.

  50. Darrell说道:

    I love this site 800 for viagra Instead, it stated that Lewthwaite was “wanted by Kenya on charges of being in possession of explosives and conspiracy to commit a felony in December 2011”. The warrant activated an international “trip wire” for Lewthwaite, Ronald K Noble, the Interpol Secretary-General, said.

  51. Teddy说道:

    Do you need a work permit? where to buy viagra online in canada But Dr Arwen Deuss, a seismologist from the University of Cambridge, commented: “This is a step in the right direction, directly comparing seismology with mineral physical properties.” She added that it should eventually provide a better understanding of the birth and evolution of our planet.

  52. Wilton说道:

    What qualifications have you got? how old should u be to take viagra The Queen and Duchess will meet the former European Ryder Cup captain during the visit and hear about his fundraising with Maggie’s. They will also meet staff, supporters and some of those who have benefited from the charity’s work.

  53. Thomas说道:

    What do you want to do when you’ve finished? viagra and cialis online This year’s fire season is part of long-term pattern of more frequent big burns, Rick Thoman, climate science manager for the National Weather Service in Alaska, said in a conference call on Thursday. Since 1988, there have been 11 summers with over 1 million acres burned in Alaska, nearly twice the rate of big-fire years recorded from 1940 to 1987, he said.

  54. Doyle说道:

    Could I have an application form? how much are viagra pills on the street Asked if it worked, Amukamara first said, “I don’t think it fazed me at all.” But the truth is, his “swag” eventually came out and he became a more aggressive player. So in some ways, he admitted, the hazing worked exactly as his teammates had hoped.

  55. Keenan说道:

    Do you have any exams coming up? how many viagra tablets should i take The Prime Minister said: “I would like you to know how hugely grateful I am for the loyalty and support you have always given me personally, and your commitment to the Government’s priorities.

  56. Franklin说道:

    Who would I report to? what is a safe site to buy viagra online The G20 meeting emphasized near-term growth and job overfiscal consolidation, because of disappointing weaknessespecially in Europe. Finance Minister Jim Flaherty did not takepart in the talks, despite travelling to Moscow, due to illness.

  57. Mauro说道:

    I’m in my first year at university levitra vs cialis vs viagra cost 143 Led Zeppelin had already amply demonstrated their groupie prowess on earlier tours. By now, they had it down, traveling with a prescribing physician and two full-service women. It did seem, though, that the groupies were younger. Jimmy Page carried on a lengthy relationship — at least for a tour — with a 14-year-old girl from Los Angeles. He had her mother’s consent.

  58. Orval说道:

    Could you tell me my balance, please? is viagra sold over the counter in france Yet, even if myself and others in similar circumstances spend more time with their parents, face up to uncomfortable questions about care and run errands for neighbours, will it make a material difference to the fabric of society?

  59. Juan说道:

    The United States do you have to see a doctor to get viagra Photographer Jon Feinstein has spent the last several years gathering images of burgers, chicken nuggets, pizzas, and French fries to examine what he says is the complexity and depth of America’s response to fast food. 

  60. Jerrell说道:

    Could you please repeat that? where can i buy viagra over the counter in canada
    After receiving condolences from fellow NFL players and other sports stars, like LeBron James, Peterson, 28, expressed his thanks on Twitter, calling pro football players “a fraternity of brothers.”

  61. Young说道:

    magic story very thanks how does levitra compared with viagra until I looked at the draft saying $6307, I have faith that…my… cousin had been actualy erning money part-time from their computer.. there neighbor has done this for under twenty months and by now repaid the depts on there home and purchased a gorgeous Ford. go to ..***.jazz77.com

  62. Jacob说道:

    I wanted to live abroad 25 mg viagra cost “That would violate every protection of minority rights that have defined the United States Senate for as long as anyone can remember. Let me assure you, this Pandora’s box, once opened, will be utilized again and again by future majorities. And it will make the meaningful consensus-building that has served our nation so well a relic — a relic of the past.” – Mitch McConnell on Senate floor, July 11, 2013

  63. Ava说道:

    We work together how many times can i take viagra in a day The five plan choices in Aon Hewitt’s private exchange carrynames used across the sector – bronze, bronze plus, silver, goldand platinum – and costs are based on the amount of coverage,says Ken Sperling, Aon Hewitt’s national health exchangestrategy leader.

  64. Santos说道:

    When can you start? where can you buy viagra online safely Why? Because many of them — including presumptive Public Advocate Letitia James and Controller Scott Stringer, four candidates for borough president and at least seven City Council members — are general election shoo-ins who do not need the money. All are guaranteed blowout victories against little-funded, far-overmatched opponents.

  65. Leigh说道:

    magic story very thanks viagra.com canada Square, which makes money by taking a 2.75 percent cut of every payment it processes, has raised the competitive ante, especially with eBay, the Web bazaar whose PayPal subsidiary is one of the dominant online payment operators.

  66. Donnie说道:

    I’m a trainee viagra kamagra jelly por ajanta pharma “The objective is to offer a consumer options, so theconsumer has low fares and then can choose what he or she wantsto add to that base fare in exchange for services,” Franke said.”That has been the manner of running Spirit, for Ryanair inEurope and we’ve taken that model to other markets as well.”

  67. Nilson说道:

    Who’s calling? sildamax viagra The digital revolution can give patients control over their own care. Patients should have the same level of access, information and control over their healthcare matters as they do in the rest of their lives.

  68. Calvin说道:

    I’d like a phonecard, please viagra tablet in india price That deal includes a new 10-year LCD glass supply agreementbetween New York-based Corning and Samsung Display, which makesLCD panels for tablets and TVs for Apple, Sony Corp andLenovo Group. Corning said the deal would add about $2billion to its annual sales.

发表评论

在发表评论前请确认您的言论中没有违反中国各项法律、法规和违背社会道德的内容。任何无意义的留言内容都会被直接删除。