Nearly 30 years of court battles over illegal arrests for loitering in New York City came to an end this week as a federal judge approved a class-action settlement that will include a $15 million payment by the city and an unusual promise that officials will work to expunge thousands of convictions.

The agreement was a milestone in a legal battle that tested government’s power to limit urban freedoms and showed how hard it can be for judges to change police practices.

The settlement came after a federal judge held the city in contempt in 2010 for “obstinance and uncooperativeness,” as the police continued for years to make arrests under laws that had been declared unconstitutional. The laws had banned loitering to panhandle or to search for a sex partner, or while in a bus or train station.

Federal and state courts struck down those laws between 1983 and 1993 as violating First Amendment rights, but some 22,000 people were charged with the offenses from 1983 to 2012.